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
If you're allowed to change your child classes source code, you can do something like that:
class Parent
{
public:
void DoSomething()
{
getMember() = 0;
}
virtual int & getMember() = 0;
};
class Child1 : public Parent
{
int childMember;
public:
int & getMember()
{
return childMember;
}
};
class Child2 : public Parent
{
int childMember;
public:
int & getMember()
{
return childMember;
}
};
Otherwise, if your object has virtual table (at least one virtual method), you can use static_cast() in combination with C++11 typeid, because it's about three times faster than dynamic_cast:
#include
class Parent
{
public:
virtual void DoSomething();
};
class Child1 : public Parent
{
public:
int childMember;
};
class Child2 : public Parent
{
public:
int childMember;
};
void Parent::DoSomething()
{
if (typeid(Child1) == typeid(*this))
{
auto child = static_cast(this);
child->childMember = 0;
}
else if (typeid(Child2) == typeid(*this))
{
auto child = static_cast(this);
child->childMember = 0;
}
};