The multiple inheritance 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: Multi-casting an object for multiple inheritance using the C++ dynamic_cast
To show: The multiple inheritance object casting using the C++ dynamic_cast
// Multiple inheritance conversion using dynamic_cast
#include <iostream>
using namespace std;
// base class
class Base1 {};
class Derived1:public Base1{};
class Derived2:public Base1{};
// derived class...
class Derived3:public Derived1, public Derived2
{
public:
virtual void funct1(){}
};
// dynamic_cast test function...
void funct2()
{
// instantiate an object
Derived3 *Test1 = new Derived3;
// -------start comment out---------
// may fail, ambiguous...from Derived3 direct conversion to Base1...
// if you use 'good' compiler, please comment out this part, there should be run time error:-)
Base1* Test2 = dynamic_cast<Base1>(Test1);
cout<<"Base1* Test2 = dynamic_cast<Base1>(Test1);"<<endl;
if(!Test2)
cout<<The> "<<Test2<<endl;
// ---------end comment out----------
// solution, traverse, recast...
// firstly, cast to Derived1
Derived1* Test3 = dynamic_cast<Derived1>(Test1);
cout<<"\nDerived1* Test3 = dynamic_cast<Derived1>(Test1);"<<endl;
if(!Test3)
cout<<"The conversion is fail..."<<endl;
else
cout<<"The conversion is successful..."<<endl;
// then cast to base1....
Base1* Test4 = dynamic_cast<Base1>(Test3);
cout<<"\nBase1* Test4 = dynamic_cast<Base1>(Test3);"<<endl;
if(!Test4)
cout<<"The conversion is fail..."<<endl;
else
cout<<"The conversion is successful..."<<endl;
}
int main(void)
{
funct2();
return 0;
}
Output example:
Base1* Test2 = dynamic_cast<Base1>(Test1);
The conversion is fail...
The pointer should be NULL ==> 00000000
Derived1* Test3 = dynamic_cast<Derived1>(Test1);
The conversion is successful...
Base1* Test4 = dynamic_cast<Base1>(Test3);
The conversion is successful...
Press any key to continue . . .