Suppose:
class A
{
public:
A *Parent;
};
class B : public A
{
protected:
B *BParent;
};
but both 'Parent' and 'BParent' in A and B need to occupy the same memory space ! The BParent in B 'is' in fact an A, but for all B objects the parent always is a B as well, and it makes it easier to access B-only functions and variables, without the need to cast Parent to B all the time in all B and from B inheriting classes and without the need to have everything virtualized in A that may be needed in B.
Is this possible ? Following obviously doesn't work, but is there something similar that does work ?
class B : public A
{
protected:
union {
A::Parent ;
B *BParent;
};
};
I'd rather avoid:
class A
{
public:
union {
A *Parent ;
class B *BParent ;
};
};
which would work. I would use this latter method if there is a way to make BParent private in A and still access it in B, so that it's hidden to all non-B objects that inherit from A.
Not entirely sure what you're asking for but here's a go.
I'm guessing you want to save some sort of access to the parent which is inherited but works for the derived types.. Maybe you're looking for this:
But it also seems like you want to preserve that A and the B...
So maybe what you're really looking for is this:
Note that if you want to use the same memory for both then they must be the same. Simply casting the pointers should do what you want.