An example of dynamic_cast

Lets look at an example of dynamic_cast where you can cast a pointer from Derived class to Base class. The example should be self explanatory:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//A very simple program to explain dynamic cast

#include <iostream>

using namespace
std;

//Base class
class A
{

public
:
int
a;
int
b;
private
:
int
c;
};


//Derived class
class B :public A
{

private
:
int
d;
};


//function that prints a and b
void function(A a)
{

cout<<"\n a = "<<a.a<<" b = "<<a.b<<endl;
}


int
main()
{

A *a;
B *b=new(B);
b->a = 20, b->b = 40;
a = dynamic_cast<A*>(b); //Dynamic cast from Dervied to Base
function(*a);
return
0;
}



The output is as follows:

Check out this stream