Tuesday, December 2, 2008

Dymanic cast

It is basically used for the safe type casting of base and derived classes.
Type casting from base class pointer to a derived class pointer is safe and does not require explicit casting, however reverse is not that much simple.
Type casting is required when we are pointing a base class object by a derived class pointer.
dynamic_cast is used for this type of herirachical casting ( upcasting ).
One pre requisite with this cast is - The base class should be polymorphic i.e. base class must have at least one virtual method.

In below example - Comment and comment out the virtual method of class A and check out the results.

#include "stdafx.h"
#include


class A
{
public :
A()
{
cout<<"A::A()"<}
~A()
{
cout<<"A::~A()"<}
//void virtual Test() {};
};


class B :public A
{
public :
B()
{
cout<<"B::B()"<}
~B()
{
cout<<"B::~B()"<}
};
int main(int argc, char* argv[])
{
try
{
A *objA = new A();
B *objB = new B();
objB = dynamic_cast(objA);
}
catch(...)
{
cout<<"error";
}
return 0;
}