devxlogo

Copy constructors

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 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.
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist