I am trying to understand Polymorphism behavior in C++ code. I got surprised by seeing the output of the the below program.
The output of the below code I was expecting some compilation error/crash at following programming statement. But output of this program quite surprised me.
p = (Class1*) &object3;
p->f();
p->g();
I couldn't understand why. I am using Visual studio 2008.
Code Snippet.
#include "stdafx.h"
#include <iostream>
using namespace std;
class Class1
{
public:
virtual void f()
{
cout << "Function f() in Class1\n";
}
void g()
{
cout << "Function g() in Class1\n";
}
};
class Class2
{
public:
virtual void f()
{
cout << "Function f() in Class2\n";
}
void g()
{
cout << "Function g() in Class2\n";
}
};
class Class3
{
public:
virtual void h()
{
cout << "Function h() in Class3\n";
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Class1 object1, *p;
Class2 object2;
Class3 object3;
p = &object1;
p->f();
p->g();
p = (Class1*) &object2;
p->f();
p->g();
p = (Class1*) &object3;
p->f();
p->g();
//p->h(); Compilation error
return 0;
}
O/P:
Function f() in Class1
Function g() in Class1
Function f() in Class2
Function g() in Class1
Function h() in Class3
Function g() in Class1