1
votes

Consider a class Base with virtual functions and a class Derived from Base implementing the virtual functions, but with few additional private members. Can we safely downcast the Base* pointer to Derived* pointer?

Base* base = new Derived();

Derived* derived = dynamic_cast<Derived*>(base); // Is this valid?

What if derived class contains an additional private member int _derivedNum apart from implementation of virtual functions in the base class? Can I still use derived->_derivedNum to access the private member of the derived class after downcasting the base class pointer?

3
It should be dynamic_cast< Derived * >.lapk
Thanks just corrected.vkaul11

3 Answers

1
votes

Yes, you certainly can. The cast is a runtime function, based on runtime type identification. If it fails, it returns a null pointer.

1
votes

Yes we can , safely downcast the Base* pointer to Derived* pointer.

Base* base = new Derived();   
Derived* derived;

//Null is returned, if the cast is not safe

if( (derived = dynamic_cast<Derived *>(base))  != NULL)
{
//cast ok, can call methods of derived class
}
0
votes

With one minor proviso, yes, that's exactly what dynamic_cast is built for.

The proviso is that your cast needs to be to pointer to Derived instead of just Derived:

Derived* derived = dynamic_cast<Derived *>(base);

But the basic point of dynamic_cast is that it first checks that the pointee object is really of the derived type, and then returns a pointer to it, or returns a null pointer if the pointee object isn't actually of (or derived from) the requested target type.

Also note that for it to work, the base class needs to contain at least one virtual function (though if it doesn't contain any virtual functions, it's probably not intended to be used as a base class anyway. There are exceptions to that (e.g., std::iterator) but they are exceptions, not the general rule.