dynamic_cast in C++
- dynamic_cast< > is used to cast one polymorphic type to another type within its
inheritance chain
- dynamic_cast< > performs a safe “downcast”
- dynamic_cast< > operations must be used on polymorphic pointers or references only.
- An incompatible pointer cast returns NULL.
- An incompatible reference cast throws a bad_cast exception.
- If you use dynamic_cast<> in the wrong place, you will get a compiler error.
- You cannot dynamic_cast<> a void *.
- You cannot dynamic_cast<> any nonpolymorphic type.
- If you have a non-polymorphic class hierarchy, use static_cast<>.
- #include <iostream>
class Base
{
public:
Base() { }
virtual ~Base() { } //Virtual Destructor
virtual void hello()
{
std::cout << "in Base";
}
};
class Derived : public Base
{
public:
void hello()
{
std::cout << "in Derived";
}
};
int main()
{
Base* basePointer = new Derived();
Derived* derivedPointer = NULL;
//To find whether basePointer is pointing to Derived type of object
derivedPointer = dynamic_cast<Derived*> ( basePointer );
if ( derivedPointer != NULL )
{
std::cout << "basePointer is pointing to a Derived class object"; //Identified
}
else
{
std::cout << "basePointer is NOT pointing to a Derived class object";
}
//Requires virtual destructor
delete basePointer;
basePointer = NULL;
return 0;
}
- RTTI (Run-time type information): Dynamically determining object's type. Two RTTI operations 1. typeid() functions--- used for generic types 2. dynamic_cast ------- for polymorphic types
- RTTI (Run-time type information) is available only for the classes which have at least one virtual function.
- For typeid(), always #include <typeinfo.h>.
- typeid() resolves polymorphic types for objects only, not pointers.
- dynamic_cast<>-ing works for pointers and references to polymorphic types, not object types
- typeid call is the one place in C++ where you can dereference a nullpointer with well-defined behavior, which implies that it can throw an exception( std::bad_typeid exception).
No comments:
Post a Comment