i'd like to discuss an inheritance problem in c++. The basic idea is to have a base class with properties and different child classes with accessors to this properties. And at the bottom shall be a class, which combines the child classes to one. It's a diamond shape, which introduces some problems.
class A {
public:
A() { prop = 1; }
int prop;
};
class B : public A {
public:
int getProp() { return prop; }
private:
B();
};
class C : public A {
public:
int setProp(int v) { prop = v; }
private:
C();
};
class D : public B, public C {
private:
D();
};
usage() {
A* a = new A();
B* b = (B*)a; // Works
b->getProp(); // Works
D* d = (D*)a; // This fails, because of diamond inheritance
d->setProp(5);// This is kindof the goal
d->getProp();// This is kindof the goal
}
So, I've read something about virtual inheritance, but I cannot achieve the casting to D, which should include all methods of B and A. Maybe I'm missing something there.
On the other hand. I really have only functions in the classes B and C, so in general it would be possible to achieve these accessors via a static wrapper taking a instance of the class. But I'd like to ask you for ideas to actually achieve it without any wrappers, which take the original A as an argument.
Edit 1: I will provide you with some scenario to clarify what I am trying to achieve. Imagine Project A, B, C, D and E
Project_A contains Class_A. This class contains some member variables.
P_A also creates 5 instances of the class.
Project_C contains Class_C.
P_C also asks P_A to get the 5 instances of C_A.
P_C sets the properties of the 5 instances via its accessors.
Project_B contains Class B.
P_B asks P_A to get the 5 instances of C_A.
P_B gets the properties of the 5 instances.
Project_D contains Class D.
P_D does set and get the properties via the accessors of C_B and C_C.
Project_E contains Class E.
Project_E works on a different property of A.
P_B knows P_A
P_C knows P_A
P_D knows P_A, P_B, P_C
P_E knows P_A
These Projects are worked on by different parties.
Maybe this helps. Maybe it doesn't. Lets see.
Edit 2: Here another pseudo code example. Maybe this way it does make more sense to you. The key may be, that A does not know which properties it holds. (or more precisely, what they mean)
class A {
map<int, int> props;
}
class B : private A {
getProp1() { return props(1)}
setProp1(int prop) { props(1) = prop }
}
class C : private A {
getProp2() { return props(2)}
setProp2(int prop) { props(2) = prop }
}
class D : public B, public C {
// This is just a combination of B and C for comfort.
}
class E : private A {
getProp3() { return props(3)}
setProp3(int prop) { props(3) = prop }
}