It is legal and sometimes necessary to cast a derived class pointer into base class pointer. This is also called upcast but by doing so the type information of the pointer gets lost.
Downcasting the pointer back to derived class requires run-time type identification (RTTI). C++ supports RTTI for polymorphic classes as they go through dynamic-binding and have type information associated with them.
TheĀ dynamic_cast operator returns a valid pointer if the object is of the expected derived type otherwise it returns a null pointer. The syntax looks like:
Derived *d_ptr = dynamic_cast < Derived * > (ptr);
This will result into an assignment if the object pointed to by ptr is of type Derived, otherwise d_ptr will become equal to NULL.
RTTI is used when it is necessary to navigate the class hierarchy. This will occur when some code is written in terms of ‘base’ class (interface) but specialized versions of this base class are to be used through derivation.
class Base
{
//polymorphic...
}
class Derived : public Base
{
//...
}
Base* readObjectFromFile()
{
//...
}
main()
{
:
Derived* derived;
//Read from file assumed to have Derived objects
Base* base = readObjectFromFile();
//need to get back Derived type!
if(derived = dynamic_cast<Derived*>(base))
{
//use derived
}
else
{
//Not of type Derived - ERROR!!
}
}


Discussion
No comments for “Run-Time Type Identification (RTTI)”