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?
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: