// file: version4.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, pure virtual is used (signified by = 0) in the base // class. This version works, because we don't try to instantiate any // base objects directly; all objects are created by virtue of instantiating // derived classes. #include #include class Base { public: virtual string op() = 0; // "pure virtual" }; 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 version 4: output of version 2: testAsBase: op() of Base testAsBase: op() of Derived_1 testAsBase: op() of Derived_1 testAsBase: op() of Derived_2 testAsBase: op() of Derived_2 testAsDerived_1: op() of Derived_1 testAsDerived_1: op() of Derived_1 testAsDerived_2: op() of Derived_2 testAsDerived_2: op() of Derived_2 */