// file: version1.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, virtual is not used at all. Consequently, the version // of op that gets called is determined strictly by the parameter type // (based or derived) through which the object is referred. #include #include class Base { public: string op() { return "op() of 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. 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() { Base ob_0; Derived_1 ob_1; Derived_2 ob_2; testAsBase(ob_0); testAsBase(ob_1); testAsBase(ob_2); testAsDerived_1(ob_1); testAsDerived_2(ob_2); } /* output of version 1: testAsBase: op() of Base testAsBase: op() of Base testAsBase: op() of Base testAsDerived_1: op() of Derived_1 testAsDerived_2: op() of Derived_2 */