Lets say I have a class A
and I also have classes B and C that inherit from class A

class A {
virtual void foo()=0;
//stuff
}

class B : class A {
void foo();
//more specific stuff
}

class C : class A {
void foo();
//more specific stuff
}

Now lets say I have a similar set up for classes X, Y, and Z, except I want them contain some form of class A
as such.

class X {
A m_myA;  
// I know this doesn't work due to the abstract definition, but this is my goal
}

class Y : class X {
B m_myA;
}

class Z : class X {
C m_myA;
}

My question is, what happens to class A in classes Y and Z? I think Y will contain an A and a B, and Z will contain an A and a C.
However, I want a pointer to a generic class X to call foo() of the most derived form of class A it contains.

So if I say

p_x->m_myA.foo(); 

If p_x is a class Y, m_myA.foo() [class B version] is called
If p_x is a class Z, m_myA.foo() [class C version] is called

Is this possible? If yes, how?
If I don't declare some version of class A in base class X, there is no way to know its a member in all derived classes

Edited 4 Years Ago by sblass92

Basically, you are on the right track, but you need to make the member variables pointers, and don't instantiate them in the derived classes. IE, something like this:

class X {
A* m_myA;  
// I know this doesn't work due to the abstract definition, but this is my goal
public:
    X(A* myA) : m_myA(myA) {}
}
class Y : class X {
B m_myB;
public:
    Y() : X(&m_myB);
}
class Z : class X {
C m_myC;
public:
    Z() : X(&m_myC) {}
}

Then, change your access code from p_x->m_myA.foo(); to this: p_x->m_myA->foo();. That should do what you want, although it is a bit clunky...

Comments
Yep, works like I want, thanks!

Excellent, this is what I wanted, thanks! It is a bit clunky. From the derived class' stand point it seems odd to have a member variable and a pointer to their own member variable, but the next best alternative I can think of is to lump class B and C back into class A and use an isB/isC flag in every class A function. A couple extra pointers and dereferences seems preferable.

This question has already been answered. Start a new discussion instead.