code
code

Reputation: 1204

Copy construction throughout inheritance chain

Shouldn't the copy constructors be used instead throughout the inheritance chain?

#include<iostream>
using namespace std;
class A
{
public:
     A(){ cout <<"1";}
     A(const A &obj){ cout <<"2";}
};

class B: virtual public A
{
public:
    B(){cout <<"3";}
    B(const B & obj){cout<<"4";}
};

class C: virtual public A
{
public:
   C(){cout<<"5";}
   C(const C & obj){cout <<"6";}
};

class D:B,C
{
public:
    D(){cout<<"7";}
    D(const D & obj){cout <<"8";}
};

int main()
{
   D d1;
   D d(d1);
}

Output:

13571358

Expected:

13572468

Upvotes: 3

Views: 113

Answers (2)

R Sahu
R Sahu

Reputation: 206697

Wouldn't the copy constructors be used instead throughout the inheritance chain?

It will be if you leave the compiler to do it for you. Since you have defined it yourself, you need to do the right thing.

D(const D & obj){cout <<"8";}

is equivalent to:

D(const D & obj) : A(), B(), C() {cout <<"8";}

You need to use:

D(const D & obj) : A(obj), B(obj), C(obj) {cout <<"8";}

to make sure that copy constructors of the base classes are called.

Upvotes: 3

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32717

The copy constructor is only used for D, because the D copy constructor does not call the copy constructors of its base classes.

It should be declared as

D(const D &obj): A(obj), B(obj), C(obj) {cout <<"8";}

unless I've mistyped something.

The A object needs to be copy constructed here since it is a virtual base class, which is constructed in the most derived class.

Upvotes: 5

Related Questions