0

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?

Eric
  • 1,183
  • 6
  • 17
  • How to copy a derived object *might* be very different than how to copy a base object. If you want the base class behaviour, you are free to in invoke it from your derived copy constructor, but it is not a given fact that you want to do so, so the language gives you the option not to. – Jesper Juhl Jan 07 '20 at 18:05
  • = default will solve your problem – JVApen Jan 07 '20 at 20:17

1 Answers1

8

Why are copy constructors different from normal constructors in this regard?

They aren't. When you do not call a base class constructor, the default constructor is called for you. This happens for every contructor.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • I guess the error in my thinking was not thinking about copy constructors as constructors. For some reason i thought they were a seperate thing. If you view a copy constructor just as a normal constructor that takes an instance of the same class as a parameter this totally makes sense now. – Eric Jan 07 '20 at 18:19
  • @Eric Anything with *constructor* in the name is a constructor. Default, "regular", copy, move, are all *constructors* – NathanOliver Jan 07 '20 at 18:23