Wednesday, August 22, 2012

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 classclass A
{
public:
  int a;
  int b;
private:
  int c;
};

//Derived classclass B :public A
{
private:
  int d;
};

//function that prints a and bvoid 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:

No comments:

Post a Comment