mopalinski
mopalinski

Reputation: 23

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

Upvotes: 0

Views: 81

Answers (2)

阴阳战士
阴阳战士

Reputation: 1

No, you can't avoid invoking parent class constructor because they are invoked in implicity. Also, you don't need to invoke them in explicity. You know, we can't imagine the successful inheritance without invoking them.

Thank you.

Upvotes: 0

SoronelHaetir
SoronelHaetir

Reputation: 15182

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.

Upvotes: 1

Related Questions