Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ copy constructor in inheritance

#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?

like image 684
Anurag Singh Avatar asked Aug 04 '18 14:08

Anurag Singh


People also ask

Can copy constructor be inherited?

Copy constructor is not inherited.

What is a copy constructor C?

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.

How are constructors called in inheritance?

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.

Can copy constructor be pass by value?

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.


1 Answers

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.

like image 151
Sam Varshavchik Avatar answered Sep 21 '22 13:09

Sam Varshavchik