C++ Multiple virtual inheritance, classes share the same subobject

59 Views Asked by At

I want to inherit 'x' from 'class B' and 'y' from 'class C' but both classes share the same 'A' subobject. Is there any solution?

#include <iostream>

class A {
    protected:
        int x;
        int y;
    public:
        A() : x(10), y(10) {}
};

class B : virtual public A {
    public:
        B() {this->x = 20; this->y = 20;}
};

class C : virtual public A {
    public:
        C() {this->x = 30; this->y = 30;}
};

class D : public B, public C {
    public:
        D() {
            this->x = this->B::x;
            this->y = this->C::y;
            std::cout << "x = " << this->x << std::endl;
            std::cout << "y = " << this->y << std::endl;
        }
};

int main() {
    D obj;
    return 0;
}

How can I solve this?

1

There are 1 best solutions below

0
Fooble On

This is one of the main problems that is solved by using composition over inheritance.

https://en.wikipedia.org/wiki/Composition_over_inheritance

Instead of inheriting from B and C your D object could contain instances of B and C. See the following example:

#include <iostream>

class A {
protected:
    int x;
    int y;
public:
    A() : x(10), y(10) {}
    
    int GetX() {
        return x;
    }
    
    int GetY() { 
        return y;
    }
};

class B : virtual public A {
public:
    B() {this->x = 20; this->y = 20;}
};

class C : virtual public A {
public:
    C() {this->x = 30; this->y = 30;}
};

class D {
public:
    D() {
        std::cout << "x = " << this->b.GetX() << std::endl;
        std::cout << "y = " << this->c.GetY() << std::endl;
    }
private:
    B b;
    C c;
};

int main() {
    D obj;
    return 0;
}