#include<iostream>
using namespace std;
class A
{
public:
A(){ cout <<"1";}
A(const A &obj){cout <<"2";}
};
class B: virtual A
{
public:
B(){cout <<"3";}
B(const B & obj):A(obj){cout<<"4";}
};
class C: virtual A
{
public:
C(){cout<<"5";}
C(const C & obj):A(obj){cout <<"6";}
};
class D:B,C
{
public:
D(){cout<<"7";}
D(const D & obj):C(obj),B(obj){cout <<"8";}
};
int main()
{
D d1;
D d(d1);
}
I am getting 13571468 as output. But I think that output should be 13572468. Why normal constructor is running instead on of copy constructor of class A?
Copy constructor is not inherited.
A copy constructor is a member function that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor.
Order of constructor call for Multiple Inheritance For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.
Passing by value (rather than by reference) means a copy needs to be made. So passing by value into your copy constructor means you need to make a copy before the copy constructor is invoked, but to make a copy you first need to call the copy constructor. Save this answer.
Your code makes a copy of an instance of D
, invoking its copy constructor.
Your class D
's copy constructor only invokes the copy constructors of its C
and B
's superclasses. Because it does not invoke A
's copy constructor, it gets default-constructed.
Virtually-inherited classes can be thought of as direct superclasses of the most-derived class. That's what virtual inheritance means. As such, in your instance of D
, its virtually-inherited A
is a direct superclass of D
, and not of B
or C
; as such, B
and C
's invocations of A
copy-constructor is not invoked.
When you have a virtually-inherited class, all your constructors really have two versions created "behind the scenes": one that's responsible for constructing any virtually-inherited classes, and one that's not. The one that's not does not call the virtually-inherited classes's constructors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With