// file: version2.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 used. Consequently, when derived objects // are referred to as members of the base class, op of the derived classes // get called. #include #include class Base { public: virtual 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. 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() { 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 2: output of version 1: testAsBase: op() of Base testAsBase: op() of Base testAsBase: op() of Derived_1 testAsBase: op() of Base testAsBase: op() of Derived_2 testAsBase: op() of Base testAsDerived_1: op() of Derived_1 testAsDerived_1: op() of Derived_1 testAsDerived_2: op() of Derived_2 testAsDerived_2: op() of Derived_2 */