Testing the class object downcast, upcast and crosscast 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: Doing various types of the C++ object castings using the dynamic_cast

To show: Testing the downcast, upcast and crosscast using the C++ dynamic_cast

 

 

 

// Testing the downcast, upcast and crosscast

// C++ object casting using dynamic_cast

#include <iostream>

using namespace std;

 

// base class

class Base1

{

public:

virtual void funct1(){};

};

 

class Derived1:public Base1

{

public:

virtual void funct2(){};

};

 

class Derived2:public Base1{

public:

virtual void funct3(){};

};

 

// derived class

class Base2

{

public:

virtual void funct4(){};

};

 

class Derived3:public Derived1,public Derived2,public Base2

{};

 

// dynamic_cast test function...

void funct5()

{

// instantiate an object Test1 of type Base2 or test1 of type Derived2 you can choose either one:-)

Base2* Test1 = new Base2;

// Derived2* Test1 = new Derived2;

// start with downcast, type Base2/Derived2 to Derived3...

Derived3* Test2 = dynamic_cast<Derived3>(Test1);

cout<<"Firstly, Derived3* Test2 = dynamic_cast<Derived3>(Test1);"<<endl;

if(!Test2)

{

cout<<"The conversion is fail lor!"<<endl;

cout<<"Checking the pointer = "<<Test2<<endl;

}

else

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

 

// Upcast, type derived3 to type derived1...

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

cout<<"\nThen, Derived1* Test3 = dynamic_cast<Derived1>(Test2);"<<endl;

if(!Test3)

{

cout<<"The conversion is fail lor!"<<endl;

cout<<"Checking the pointer = "<<Test3<<endl;

}

else

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

 

// crosscast, direct, type Base2/Derived2 to Derived1...

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

cout<<"\nThen, Derived1* Test4 = dynamic_cast<Derived1>(Test1);"<<endl;

if(!Test4)

{

cout<<"The conversion is fail lor!"<<endl;

cout<<"Checking the pointer = "<<Test3<<endl;

}

else

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

delete Test1;

}

 

int main(void)

{

funct5();

return 0;

}

 

Output example:

 

Firstly, Derived3* Test2 = dynamic_cast<Derived3>(Test1);

The conversion is fail lor!

Checking the pointer = 00000000

Then, Derived1* Test3 = dynamic_cast<Derived1>(Test2);

The conversion is fail lor!

Checking the pointer = 00000000

Then, Derived1* Test4 = dynamic_cast<Derived1>(Test1);

The conversion is fail lor!

Checking the pointer = 00000000

Press any key to continue . . .

 

 

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