Search code examples
c++constructormultiple-inheritance

How do I avoid explicitly constructing everything inherited in an initializer list in C++?


When I construct an object D I need to include the constructors for A, B, and C in the initializer list. Is there any way to make it so that I don't need all three in the initializer list or not?

If I try to initialize D using only a constructor for B I get an error because I don't have a default constructor for A or C. If I add a default constructor for A and C I get issues with "i" being reinitialized with no value.

#include <iostream>
using namespace std;

class A 
{
    int i;
public:
    A(int ii) :
        i(ii)
    {}

    ~A() { }

    int getI() { return i; }
};

class B : public virtual A
{
public:
    B(int ii) :
        A(ii)
    { }

    ~B() { }
};

class C : public virtual A 
{
public:
    C(int ii) :
        A(ii)
    { }

    ~C() { }
};

class D : public B, public C 
{
public:
    D(int ii) :
        A(ii), B(ii), C(ii)
    { }
    ~D() { }

 };

int main() 
{
    D d(45);
    cout << d.getI() << endl;
}

Solution

  • If you add default constructors to A, B, and C, the implmentation of D becomes a bit simpler.

    #include <iostream>
    using namespace std;
    
    class A 
    {
       int i;
       public:
       A() : i(0) {}
       A(int ii) : i(ii) {}
    
       ~A() { }
    
       int getI() { return i; }
    };
    
    class B : public virtual A
    {
       public:
          B() { }
          B(int ii) : A(ii) { }
    
          ~B() { }
    };
    
    class C : public virtual A 
    {
       public:
          C() { }
          C(int ii) : A(ii) { }
    
          ~C() { }
    };
    
    class D : public B, public C 
    {
       public:
    
          // Relies on default constructors of the other classes.
          D() { }
    
          // Relies on the default constructors of B and C.
          D(int ii) : A(ii) { }
          ~D() { }
    
    };
    
    int main() 
    {
       D d1(45);
       D d2;
       cout << d1.getI() << endl;
       cout << d2.getI() << endl;
    }