The upcasting conversion using the dynamic_cast 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: Casting the object type from derived to base class in C++ program
To show: The upcasting conversion using dynamic_cast type caster in C++ programming
// Upcast conversion using dynamic_cast
#include <iostream>
using namespace std;
//base class
class Base1 {};
// derived class...
class Derived1:public Base1 {};
// another derived class
class Derived2:public Derived1{};
// dynamic_cast test function...
void funct1()
{
// instantiate an object
Derived2* Test1 = new Derived2;
// upcasting, from derived class to base class, Derived1 is a direct from Base1
// making Test2 pointing to Derived1 sub-object of Test1
Derived1* Test2 = dynamic_cast<Derived1>(Test1);
cout<<"Derived1* Test2 = dynamic_cast<Derived1>(Test1);"<<endl;
if(!Test2)
cout<<"The conversion is fail..."<<endl;
else
cout<<"The conversion is successful..."<<endl;
// upcasting, from derived class to base class, Derived2 is an indirect from Base1
Base1* Test3 = dynamic_cast<Derived1>(Test1);
cout<<"\nBase1* Test3 = dynamic_cast<Derived1>(Test1);"<<endl;
if(!Test3)
cout<<"The conversion is fail..."<<endl;
else
cout<<"The conversion is successful..."<<endl;
}
int main(void)
{
funct1();
return 0;
}
Output example:
Derived1* Test2 = dynamic_cast<Derived1>(Test1);
The conversion is successful...
Base1* Test3 = dynamic_cast<Derived1>(Test1);
The conversion is successful...
Press any key to continue . . .