// virtual.welcome.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include using namespace std; struct VirtAbstract { virtual void p1() = 0; }; struct VirtBase : public VirtAbstract { int var; virtual VirtBase& operator << (int a) { cout << "\tVirtBase operator " << endl; var = a; return *this; } virtual void p1() { cout << "\tprint VirtBase virtual call \n"; }; void p2() { cout << "\tprint VirtBase NON-virtual call \n"; }; }; struct VirtInherit : public VirtBase { int var2; virtual VirtInherit& operator << (int a) { cout << "\tVirtInherit operator " << endl; var2 = a; return *this; } virtual void p1() { cout << "\tprint VirtInherit virtual call \n"; }; void p2() { cout << "\tprint VirtInherit NON-virtual call \n"; }; }; // struct Base { int a; void m() { cout << "\tBase method called " << endl; } }; struct Inherit : public Base { void m() { cout << "\tInherit method called " << endl; } int b; }; // introspection? int main() { Inherit classicObj; ((Base&)classicObj).m(); // calls the base class method // since the call depends // on the left hand side type // evaluated from the expression VirtBase baseObject; VirtInherit inheritedObject; VirtBase* ary[3]; ary[0] = &baseObject; ary[1] = &inheritedObject; ary[2] = 0; for (int i=0;i<3;i++) if (ary[i]) { cout << "working with object " << i << endl; VirtInherit* cobj = (VirtInherit*) ary[i]; cobj->p1(); // calls appropriate VIRTUAL method cobj->p2(); // calls always the VirtBase p2() method *cobj << 5; } return 0; }