I'm having a bit of trouble finding the info I need about copy constructors. Actually, I'm having a bit of trouble figuring out the right way to use them in the first place.

My question: How do I correctly call copy constructors for a derived class so that it correctly copies data from the base class as well? Here's what I've come up with.

class Base
{
Base();
Base(const Base &theObject);
int baseData;
int GetData1() const {return baseData;}
};

Base::Base(const Base &theObject)
{
baseData = theObject.GetData1() ;
}

class Derived : public Base
{
Derived();
Derived(const Derived &theObject);
int derivedData;
int GetData2() const {return baseData;}
}

Derived:: Derived( const Derived &theObject)
{
Base( &theObject );
derivedData = theObject.GetData2();
}


Is this what a copy constructor is supposed to do?

Recommended Answers

All 4 Replies

Ya, sorta, but you want Base( theObject ) between the declaration and the brace:

Derived:: Derived( const Derived& theObject )

: Base( theObject )

{
<further initialization>
}

(watch those &'s, they should be in the declaration, but not in the call)

hmm. still tricky, but I think I get it.

Thanks. You're my huckleberry, chainsaw.

(that's not a string of words one hears often)

You can also do the same for the = operator.

Base operator=(const Base& rhs)
{
//copy Base
}

Derived operator=(const Derived& rhs)
{
Base::operator=(rhs);
//copy derived
}

In case anyone was curious.

commented: Only 5 years too late. -5

Expressions like

Base( &theObject );

don't behave the way you expect them to. This expression invokes Base's constructor to create a new temporary instance of Base, which is immediately destroyed at then end of the expression, since it isn't in scope (it's unnamed). It has no effect on the current instance (this). To invoke parent (copy) constructors, you need to use an initialization list.

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.