Copy constructors

Copy constructors

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

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 anconsistent state. Note that if you do not call the copy constructorof the base class explicitly, the default constructor of theBase 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.


Share the Post: