I have one base class and two classes derived from it. I have several virtual functions in the base class so I create a pointer to the base class and use this pointer to access these methods.
Now I want to access member variable of derived class (this variable is not present in the base class) using the pointer to base class which points to a derived class object.
Can this be done? Should this be done?
Yes you can do it, but it is not recommended. You can use dynamic_cast to cast the base class pointer to the derived class pointer and get the variables in the derived class.
For example, if you have a base clas called Base and two derived classes Derived1 and Derived2, and if you have
Base* p
pointer then you can do:Why do you want to access the derived class' interface? When you use polymorphism, you shouldn't need to care about what's behind a base class reference/pointer. If you do, then that's usually a hint at a design flaw.
What you are trying to do is a "switch-on-type". ("If behind
B*
is aD1
object, do this, otherwise do that".) A switch-on-type is circumventing polymorphism and a bad sign.Note: There is a way to do this (
dynamic_cast
), but for the reasons mentioned above I consider this bad practice and won't elaborate on it.Just move that variable to the base class. The only case when Base class need to call methods (or to use variables) of Derived class is Curiously recurring template pattern when it implements static polymorphism. In other cases it looks like bad design.
Write a virtual function, that would act accordingly in each of the classes, and in the place where you actually "need" to access the variable - call that function. It's that simple.