// Quest for Dynamic Dispatch in C++ using namespace std; #include // 1. Pry to the gods when all planets are aligned .... class A { protected: int x; public: A(int y) {x=y;} void f() { cout << "A.f, x is "<< x << endl; } virtual void g() { cout << "A.g\n"; } }; class B : public A // public inheritance: publics stay public ("is a") { public: B(int y) : A(y*2) {} void f() { cout << "B.f, x is "<< x << endl; } void g() { cout << "B.g\n"; } }; int main() { A n(1); B m(1); n = m; // What's the "type" of this object? n.f(); n.g(); // still prints A.g ! // only static dispatch is available here, despite virtual A *p = new B(1); p->f(); // still calls A.f p->g(); // finally calls B.g DYNAMIC DISPATCH AT LAST! return 0; }