1

Say I have several classes that inherit like so.

#include <iostream>

struct A {
    A() {std::cout << "a";}
};

struct B : A {};
struct C : A {};

struct D : B, C {};

int main {
    D d;
}

On executing the program, as expected, I see two A objects were constructed, one for the B and one for the C object that are constructed when creating a D object. Whoever, how can I not create two A objects? I want the same A object to be used to create B and C objects. Is this possible?

ChemiCalChems
  • 612
  • 12
  • 31
  • 2
    Possible duplicate of [C++, are multiple-inherited constructors called multiple times?](http://stackoverflow.com/questions/7405839/c-are-multiple-inherited-constructors-called-multiple-times) – Danh Nov 03 '16 at 10:39

3 Answers3

7

If B and C both use virtual inheritance for A, then there will only be a single base class object for each D object:

struct B : virtual A {};
struct C : virtual A {};

//...
D d; //prints "a" rather than "aa" 

Live demo

Community
  • 1
  • 1
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
2

If you're looking for a non-polymorphic solution, you're out of luck. Otherwise, change to the following:

struct B : virtual A {};
struct C : virtual A {};
DeiDei
  • 10,205
  • 6
  • 55
  • 80
1

As written, every D object has two sub-objects of type A, one inherited from class B and one inherited from class C. So the constructor of A must run twice, once for each sub-object.

If the original design is wrong, and there should only be one A sub-object, despite the use of two bases B and C, the change is to make A a virtual base of B and a virtual base of C. That way there will only be one A sub-object in a D object, and the constructor of A will only run once when a D object is constructed.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165