/* Extending a class with a method, subject to dynamic dispatch, using double unsafe type cast (two wrongs make a right?) */ using namespace std; #include #include class A { public: int x; A(int z) {x=z;} virtual void f() { cout << "A.f" << endl; } }; class B : public A { public: double y; B(int a, double b):A(a) {y=b;} virtual void f() { cout << "B.f" << endl; } }; // Now I want to add an additional capability to classes A,B (void g()): // adapter class that adds a new method to A, subject to dynamic dispatch class AX // to be used in the form ((AB*)n->g() where A* g; { public: static void gg(A *n) { cout << "AX.gg, x is " << n->x << endl; } void g() { gg( (A*)this ); } // don't mark as virtual }; class BX { public: static void gg(B *n) { cout << "BX.gg, x, y are " << n->x << " , " << n->y << endl; } void g() { gg( (B*)this ); } }; int main() { A *n = new A(5); A *m = new B(2,3.5); ((AX*)n)->g(); ((BX*)m)->g(); // extension methods can override this way return 0; } // this is not dynamic dispatch: in fact 'virtual' will mess it up. // It's just a trick to get C++ to call the function you want.