views:

252

answers:

2

Hello,

I have a question regarding the C++ Standard.

Suppose you have a base class with user defined copy constructor and assignment operator. The derived class uses the implicit one generated by the compiler.

Does copying / assignment of the derived class call the user defined copy constructor / assignment operator? Or do you need to implement user defined versions that call the base class?

Thank you for your help.

A: 

Only if the derived class has an explicitly defined operator function. Otherwise, the op function of the parent class is called. Otherwise, the implicit C++ one is called.

Delan Azabani
+2  A: 

If a derived class does not declare a copy constructor, and implicit one will be declared (12.8/4 "Copying class objects") - even if the base class has a user-delcared and defined copy constructor. If the base class has a user-defined copy constructor in this case, that base class sub-object is copied using that user-defined copy ctor (12.8/8).

Similarly for copy assignment operators (12.8/10 and 12.8.13).

So you do not necessarily need to implement user defined versions that call the base class if the derived class doesn't need a user-defined copy ctor or copy assignment operator for 'its own stuff'. However, if the derived class does declare and define its own copy ctor/copy assignment operator, then those user-defined implementations are responsible for doing the right thing as far as the base class sub-object is concerned - that is no longer handled by the compiler automatically.

Michael Burr
thank you very much.
Tobias Langner