//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:
That's a really bad and pointless example.
ReplyDeleteYour 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.
Hi Candy,
ReplyDeleteI 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!
"A man wrapped up in himself makes a very small bundle."
ReplyDeleteBenjamin Franklin