Sams Teach Yourself C++ in 21 Days

(singke) #1
The rule of thumb is this: If any of the functions in your class are virtual, the destructor
should be as well.

400 Day 12


You should have noticed that the listings in today’s lesson have been includ-
ing virtual destructors. Now you know why! As a general practice, it is wise
to always make destructors virtual.

NOTE

Virtual Copy Constructors ..............................................................................


Constructors cannot be virtual, and so, technically, no such thing exists as a virtual copy
constructor. Nonetheless, at times, your program desperately needs to be able to pass in a
pointer to a base object and have a copy of the correct derived object that is created. A
common solution to this problem is to create a Clone()method in the base class and to
make that be virtual. The Clone()method creates a new object copy of the current class
and returns that object.
Because each derived class overrides the Clone()method, a copy of the derived class is
created. Listing 12.11 illustrates how the Clone()method is used.

LISTING12.11 Virtual Copy Constructor
1: //Listing 12.11 Virtual copy constructor
2: #include <iostream>
3: using namespace std;
4:
5: class Mammal
6: {
7: public:
8: Mammal():itsAge(1) { cout << “Mammal constructor...\n”; }
9: virtual ~Mammal() { cout << “Mammal destructor...\n”; }
10: Mammal (const Mammal & rhs);
11: virtual void Speak() const { cout << “Mammal speak!\n”; }
12: virtual Mammal* Clone() { return new Mammal(*this); }
13: int GetAge()const { return itsAge; }
14: protected:
15: int itsAge;
16: };
17:
18: Mammal::Mammal (const Mammal & rhs):itsAge(rhs.GetAge())
19: {
20: cout << “Mammal Copy Constructor...\n”;
21: }
22:
23: class Dog : public Mammal
Free download pdf