The void pointer and dynamic_cast of the C++ class object
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 C++ class object to the void pointer using dynamic_cast
To show: The void pointer and dynamic_cast of the C++
// If new_name is void*, the result of casting is a pointer to the complete object pointed to by the expression
// void* and dynamic_cast
#include <iostream>
using namespace std;
// base class
class Base1
{
public:
virtual void funct1(){};
};
// another base class...
class Base2
{
public:
virtual void funct2(){};
};
// dynamic_cast test function...
void funct3()
{
// instantiate objects
Base1 * Test1 = new Base1;
Base2 * Test2 = new Base2;
// making Test3 pointing to an object of type Base1
void* Test3 = dynamic_cast<void>(Test1);
cout<<"void* Test3 = dynamic_cast<void>(Test1);"<<endl;
if(!Test3)
cout<<"The conversion is fail..."<<endl;
else
cout<<"The conversion is successful..."<<endl;
// making Test3 pointing to an object of type Base2
Test3 = dynamic_cast<void>(Test2);
cout<<"\nTest3 = dynamic_cast<void>(Test2);"<<endl;
if(!Test3)
cout<<"The conversion is fail..."<<endl;
else
cout<<"The conversion is successful..."<<endl;
}
int main(void)
{
funct3();
return 0;
}
Output example:
void* Test3 = dynamic_cast<void>(Test1);
The conversion is successful...
Test3 = dynamic_cast<void>(Test2);
The conversion is successful...
Press any key to continue . . .