c++virtual-inheritance

virtual multiple inheritance constructor


I'm working on a C++ code example that uses virtual inheritance and multiple inheritance. In my code, I've noticed that I have to call the constructor of the Base class in each derived class, even though the values passed to the base class constructor are not used. Why is this necessary, and can I avoid calling the base class constructor in every derived class and only call it in the Combined class?

#include <stdio.h>

class Base
{
    public:
        Base(int n) : n(n) {}
        int n;
};

class AddsSomething1 : virtual public Base
{
    public:
        AddsSomething1() : Base(1)
        {
            printf("AddsSomething1(): base %d\n", this->n);
        }

        int something1;
};

class AddsSomething2 : virtual public Base
{
    public:
        AddsSomething2(): Base(2)
        {
            printf("AddsSomething2(): base %d\n", this->n);
        }

        int something2;
};

class AddsSomething3 : virtual public Base
{
    public:
        AddsSomething3() : Base(3)
        {
            printf("AddsSomething3(): base %d\n", this->n);
        }

        int something3;
};

class Combined : public AddsSomething1, public AddsSomething2, public AddsSomething3
{
    public:
        Combined(int n) : Base(123)
        {
            printf("Combined(): base %d\n", this->n);
        }
};

int main()
{
    Combined(123);
}

Output:

AddsSomething1(): base 123
AddsSomething2(): base 123
AddsSomething3(): base 123
Combined(): base 123

Solution

  • A virtual base's constructor must be invoked from every derived type because it is always and only the single most-derived type constructor that actually invokes the virtual bases constructor. Every other base in the inheritance chain learns that the virtual base has already been constructed and skips that step.