ChemiCalChems ChemiCalChems - 1 year ago 62
C++ Question

Avoid calling base constructor 2 times

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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download