// file: version7.cc // author: keller // purpose: demonstrating use of virtual destructors // // 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" virtual ~Base() { } }; class Derived_1 : public Base { public: string op() { return "op() of Derived_1"; } ~Derived_1() { cout << "Derived_1 destructor called" << endl; } }; class Derived_2 : public Base { public: string op() { return "op() of Derived_2"; } ~Derived_2() { cout << "Derived_2 destructor called" << endl; } }; // 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_1 = new Derived_1; Base *ob_2 = new Derived_2; testAsBase(*ob_1); testAsBase(*ob_2); delete ob_1; delete ob_2; } /* output of version 7: output of version 6: testAsBase: op() of Derived_1 testAsBase: op() of Derived_1 testAsBase: op() of Derived_2 testAsBase: op() of Derived_2 Derived_1 destructor called Derived_2 destructor called */