Ok I admit it, I'm a total C++ noob.
I was checking the book Data Structures and algorithms in C++ by Adam Drozdek, in the section 1.5 : "Polymorphism" he proposes the next example:
class Class1
{
public:
virtual void f()
{
cout << "Function f() in Class1" << endl;
}
void g()
{
cout << "Function g() in Class1" << endl;
}
};
class Class2
{
public:
virtual void f()
{
cout << "Function f() in Class2" << endl;
}
void g()
{
cout << "Function g() in Class2" << endl;
}
};
class Class3
{
public:
virtual void h()
{
cout << "Function h() in Class3" << endl;
}
};
int main()
{
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(); // Abnormal program termination should occur here since there is
// no f() method in object3, instead object3->h() is called
p->g();
//p->h(); h() is not a member of Class1
return 0;
}
I compiled this using Visual Studio 2010, and two things happened:
- First there was no "abnormal termination" in the line
p->f()
- The method
h()
of object3 is called in the line where the "abnormal termination" should occur.
The output of the programs is:
Function f() in Class1 Function g() in Class1 Function f() in Class2 Function g() in Class1 Function h() in Class3 Function g() in Class1
I´m trying to understand why this happens, but it seems too strange for me.
Any help would be great.
Thanks in advance!