From my understanding, when creating an object of a derived class the base class constructor get's automatically called (in case a one without parameters exists). This seems to not be the case for copy constructors:
#include <iostream>
class Base
{
public:
Base()
{
std::cout << "Base Constructor called" << std::endl;
}
Base(const Base& ref)
{
std::cout << "Base Copy Constructor called" << std::endl;
}
};
class Derived : Base
{
public:
Derived()
{
std::cout << "Derived Constructor called" << std::endl;
}
Derived(const Derived& ref) //: Base(ref) // <- without this Base copy constructor doesnt get called
{
std::cout << "Derived Copy Constructor called" << std::endl;
}
};
int main()
{
Derived d1;
Derived d2 = d1;
return 0;
}
Output without ": Base(ref)" :
Base Constructor called Derived Constructor called Base Constructor called Derived Copy Constructor called
Output with ": Base(ref)" :
Base Constructor called Derived Constructor called Base Copy Constructor called Derived Copy Constructor called
So unless you explicitly call the Base class copy constructor a new Base class object gets created instead of being copy constructed. So i guess only the Derived class members get actually copy constructed while all Base class members would be newly created by the Base class constructor. Now for me this seems like something you never really want. If you copy construct an object you expect all members to be copied instead of just a part of them.
Why are copy constructors different from normal constructors in this regard?