1

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;
}
  • You need to construct the A,B,C base class objects, there is no avoiding that. You can make default constructors without getting "issues" as you say although nobody can help with that without seeing your code. – M.M Feb 19 '19 at 02:53

3 Answers3

1

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;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • When d1 is initialized, when do the default constructors for B and C get called? I would have thought that A(ii) would be called and then the default constructors for B and C would reinitialize i to have no value – PolarPenguin Feb 19 '19 at 02:59
  • @PolarPenguin, when the `B` and `C` sub-objects of `D` get initialized, they are not going to initialize the `A` sub-object. Hence, `i` won't be reinitialized. That is guaranteed by the standard. – R Sahu Feb 19 '19 at 03:02
0

I'm afraid not. With virtual inheritance, your most-derived class must initialise the virtual base.

Read more here.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

How about adding a default value to the A, B, C constructors, i.e.

A(int ii=0) :
J.R.
  • 1,880
  • 8
  • 16
  • Sorry, should only be the B, C constructors with default value then you can intialise with D(int ii):A(ii) – J.R. Feb 19 '19 at 03:31