I'm trying to clean up my coding a bit for a program I'm working on. Here's an example of my code (not my exact code, but I've adapted it to an example):

class Example
{
private:
    double* group;
    int number;
public:
    Example() {group=new double[1]; number=0;};
    Example(const Example& ex);
    Example& Example::operator=(const Example& ex);
    void function1(const Example& ex);
};

Example::Example(const Example& ex)
{
        number=ex.number;
        if(ex.group)
        {
            group=new double[number+1];
            for(int i=number;i>=0;i--)
                group[i]=ex.group[i];
        }
        else group=0;
}


Example& Example::operator=(const Example& ex)
{
    if(this == &ex)
        return *this;

    delete [] group;
    number=ex.number;

    if(group != ex.group)
    {
        group=new double[number+1];
        for(int i=number;i>=0;i--)
            group[i]=ex.group[i];
    }
    else group=0;
    return *this;
}

I want to be able to create a copy object of Example that is the same as the original. I've created a copy constructor and overloaded the assignment operator, but if I call the member function from within main, then in my definition of the member function function1, how can I create a copy for computational purposes? This is what I've been doing, but I feel like there's an easier way:

Example copy2;
        copy2.number=number;
        copy2.group=new double[number+1];
        for(int i=number;i>=0;i--)
            copy2.group[i]=group[i];

(Sorry if this is confusing, let me know and I'll try to explain a different way if need be)
Thanks!

Recommended Answers

All 6 Replies

void Example::function1( const Example& ex )
{
    Example copy_of_ex( ex ) ;

    /* whatever */

}
void Example::function1( const Example& ex )
{
    Example copy_of_ex( ex ) ;

    /* whatever */

}

I want the copy to contain the attributes of the original object in which it is being called from the main.

int main()
{
    Example doe;
    Example water;
    
    doe.function1(water);
}

I want to make a copy that has the attributed of doe to use within function1.

simply

int main()
{
    Example doe;
    
    doe.function1(doe);
}

or

int main()
{
    Example doe;
    Example water(doe);
    
    doe.function1(water);
}

water and doe are two different objects that are supposed to hold different information. I want to create a third object, within doe's calling of function1 (within the definition of function1), that has the same attributes of doe.

void Example::function1( const Example& ex )
{
    // copy of the object on which function1 is called
    Example copy_of_this( *this ) ;

    /* whatever */

}

Ohh ok I see. That should help me a lot! Thank you very much for your patience.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.