If you are allowed to modify the source code of your child classes, you can do something like this:
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 a virtual table (at least one virtual method), you can use static_cast () in combination with the C ++ 11 typeid, because it is about three times faster than dynamic_cast:
#include <typeinfo> 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<Child1*>(this); child->childMember = 0; } else if (typeid(Child2) == typeid(*this)) { auto child = static_cast<Child2*>(this); child->childMember = 0; } };
source share