// file: version5.cc // author: keller // purpose: demonstrating use of virtual methods // // description: // There is a base class and two derived classes. // Each overloads a method 'op'. // // In this version, op is omitted from the base class altogether. // Even though it is defined in the derived classes, it can't be called // in testAsBase, since there is no placeholder method. #include #include class Base { }; class Derived_1 : public Base { public: string op() { return "op() of Derived_1"; } }; class Derived_2 : public Base { public: string op() { return "op() of Derived_2"; } }; // Note that the test objects are passed by reference. If we passed the // parameter to testAsBase by value, a copy constructor would get called, // which would change the result, since only the base portion would get copied, // and the base method would always get called. void testAsBase(Base &object) { cout << "testAsBase: " << object.op() << endl; } void testAsDerived_1(Derived_1 &object) { cout << "testAsDerived_1: " << object.op() << endl; } void testAsDerived_2(Derived_2 &object) { cout << "testAsDerived_2: " << object.op() << endl; } main() { Derived_1 ob_1; Derived_2 ob_2; testAsBase(ob_1); testAsBase(ob_2); testAsDerived_1(ob_1); testAsDerived_2(ob_2); } /* output of version5 (compiler): version5.cc: In function `void testAsBase(class Base &)': version5.cc:50: no matching function for call to `Base::op ()' */