Change type of base class variable in controlled situation?

110 views Asked by At

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.

1

There are 1 answers

1
u8sand On

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:

template <class T>
class A
{
private:
    T *parent;
};

class B : public A<B>
{

};

But it also seems like you want to preserve that A and the B...

So maybe what you're really looking for is this:

class A
{
protected:
    A *AParent() { return parent; }
protected:
    A *parent;
};

class B : public A
{
protected:
    B *BParent() { return (B*)parent; };
};

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.