I am facing a situation where I need to access child member variables inside the parent class. I know this is against OO principles but I have to deal with a scenario where
Would making an intermediate abstract class that contains the childMember you need to access be an option?
If so:
class Parent
{
virtual void DoSomething() //Parent must be a polymorphing type to allow dyn_casting
{
if (AbstractChild* child = dynamic_cast<AbstractChild*>(this)) {
child->childMember = 0;
} else //Its not an AbstractChild
}
}
class AbstractChild : Parent
{
int childMember;
virtual void DoSomething() = 0;
}
class Child1 : AbstractChild {
virtual void DoSomething() { }
}
static_cast<Child*>(this)->childMember = 0;
should work.
You can use the curiously recurring template pattern to achieve this.
template<typename T>
class Parent
{
void DoSomething()
{
// This is what I need
T::childMember = 0;
}
virtual ~Parent() {}
};
class Child1 : Parent<Child1>
{
int childMember;
friend class Parent<Child1>;
};