The downcast object casting using the C++ dynamic_cast

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Casting an object from parent to child using the C++ dynamic_cast

To show: Downcast conversion using dynamic_cast object casting from parent to child

 

 

// Downcast conversion using dynamic_cast

#include <iostream>

using namespace std;

 

// base class

class Base1 {

public:

virtual void funct1(){};

};

 

// derived class...

class Derived1:public Base1 {

public:

virtual void funct2(){};

};

 

// dynamic_cast test function...

void funct3()

{

// instantiate objects

Base1* Test1 = new Derived1;

Base1* Test2 = new Base1;

 

// making Test1 pointing to Derived1

Derived1* Test3 = dynamic_cast<Derived1>(Test1);

cout<<"Derived1* Test3 = dynamic_cast<Derived1>(Test1);"<<endl;

if(!Test3)

cout<<"The conversion is fail..."<<endl;

else

cout<<"The conversion is successful..."<<endl;

 

// should fails coz Test2 pointing to Base1 not Derived1, Test4 == NULL

Derived1* Test4 = dynamic_cast<Derived1>(Test2);

cout<<"\nDerived1* Test4 = dynamic_cast<Derived1>(Test2);"<<endl;

if(!Test4)

cout<<"The conversion is fail..."<<endl;

else

cout<<"The conversion is successful..."<<endl;

 

// reconfirm, should be NULL pointer

cout<<"Should be NULL pointer = "<<Test4<<endl;

}

 

int main(void)

{

funct3();

return 0;

}

 

Output example:

 

Derived1* Test3 = dynamic_cast<Derived1>(Test1);

The conversion is successful...

Derived1* Test4 = dynamic_cast<Derived1>(Test2);

The conversion is fail...

Should be NULL pointer = 00000000

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index