The bad_cast and RTTI C++ program example

 

 

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: Trying the dynamic_cast to show the bad_cast and RTTI usage

To show: The bad_cast and RTTI C++ code sample

 

 

// The bad_cast

// Need to enable the Run-Time Type Info, rtti of your compiler/IDE.

#include <typeinfo>

#include <iostream>

using namespace std;

 

class Myshape

{

public:

virtual void myvirtualfunc() const {}

};

 

class mytriangle: public Myshape

{

public:

virtual void myvirtualfunc() const

{ };

};

 

int main(void)

{

Myshape Myshape_instance;

Myshape &ref_Myshape = Myshape_instance;

 

try {

//try the run time typecasting, dynamic_cast

mytriangle &ref_mytriangle = dynamic_cast<mytriangle>(ref_Myshape);

}

 

catch (bad_cast) {

cout<<"Can't do the dynamic_cast lor!!!"<<endl;

cout<<"Caught: bad_cast exception. Myshape is not mytriangle.\n";

}

}

 

Output example:

 

Can't do the dynamic_cast lor!!!

Caught: bad_cast exception. Myshape is not mytriangle.

Press any key to continue . . .

 

 

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