Copy constructor in derived class

Reply

Join Date: Sep 2004
Posts: 4
Reputation: elspork is an unknown quantity at this point 
Solved Threads: 0
elspork elspork is offline Offline
Newbie Poster

Copy constructor in derived class

 
0
  #1
Sep 28th, 2004
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?
Reply With Quote Quick reply to this message  
Join Date: Jun 2004
Posts: 436
Reputation: Chainsaw is an unknown quantity at this point 
Solved Threads: 10
Chainsaw's Avatar
Chainsaw Chainsaw is offline Offline
Unprevaricator

Re: Copy constructor in derived class

 
0
  #2
Sep 28th, 2004
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)
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 4
Reputation: elspork is an unknown quantity at this point 
Solved Threads: 0
elspork elspork is offline Offline
Newbie Poster

Re: Copy constructor in derived class

 
0
  #3
Sep 29th, 2004
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)
Reply With Quote Quick reply to this message  
Join Date: Sep 2009
Posts: 1
Reputation: Tarqquin is an unknown quantity at this point 
Solved Threads: 0
Tarqquin Tarqquin is offline Offline
Newbie Poster

Re: Copy constructor in derived class

 
0
  #4
Sep 30th, 2009
You can also do the same for the = operator.

  1. Base operator=(const Base& rhs)
  2. {
  3. //copy Base
  4. }
  5.  
  6. Derived operator=(const Derived& rhs)
  7. {
  8. Base::operator=(rhs);
  9. //copy derived
  10. }

In case anyone was curious.
Reply With Quote Quick reply to this message  
Reply

Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC