Monday 22 June 2009

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:

3 comments:

  1. That's a really bad and pointless example.

    Your cout can be replaced by:
    cout << "\n a = " << a.A::a << " b = " << a.b << endl;

    to always use the one from the A class.

    Your dynamic cast can just be removed for the same effect.

    ReplyDelete
  2. Hi Candy,

    I agree. The point in this blog is not to show great or optimised code. I am just explaining the concepts with the help of very simple examples. Please feel free to add your own examples in the comments section.

    Thanks!

    ReplyDelete
  3. "A man wrapped up in himself makes a very small bundle."

    Benjamin Franklin

    ReplyDelete