#include #include using namespace std; // Overloading versus Overriding in C++ struct A { virtual int f() { return 1; } // note "virtual" }; struct B : public A { int f() override { return 2; } // note "override" }; int g(A* x) { return 10; } int g(B* x) { return 20; } int main() { A* n = new B(); cout << n->f() << endl; // prints 2 (overloading = dynamic dispatch) cout << g(n) << endl; // prints 10 (overriding = resolved statically). } /* In C++, to have the default behavior of Java we must 1. use public inheritance to establish "is a" relationship between B and A 2. use dynamic memory allocation (as opposed to stack allocation) because the compiler doesn't know exact type and size of object to be created. Only classes that contain/override virtual methods will have dynamic type information attached to objects at runtime. */