Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Mar 27, 1997

Copy constructors

Question:
I have a class with multiple parents. In my copy constructor, should I invoke the parents' copy constructor or their default constructor?

Answer:
In all but the rarest of cases, you want to call the copy constructor of the base class. This ensures that the entire object is copied and is in an consistent state. Note that if you do not call the copy constructor of the base class explicitly, the default constructor of the Base class is called. This may not be desirable and could be dangerous.

For example:

class Base 
{
public:
	Base();
	Base(const Base&b);
};

class Derived : public base
{
public:
	Derived(const Derived&d): Base(d) // calls Base::Base(const Base &)
	{
	}
	Derived();
};

class Derived1 : public base
{
public:
	Derived1(const Derived1&d) // calls Base::Base()
	{
	}
	Derived();
};
Hope this helps.
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date