954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Copy constructor in derived class

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?

elspork
Newbie Poster
4 posts since Sep 2004
Reputation Points: 10
Solved Threads: 0
 

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

Derived:: Derived( const Derived& theObject )

: Base( theObject )

{

}

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

Chainsaw
Posting Pro in Training
436 posts since Jun 2004
Reputation Points: 36
Solved Threads: 11
 

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)

elspork
Newbie Poster
4 posts since Sep 2004
Reputation Points: 10
Solved Threads: 0
 

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.

Tarqquin
Newbie Poster
1 post since Sep 2009
Reputation Points: 5
Solved Threads: 0
 

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.

barfoo
Newbie Poster
1 post since Dec 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You