|
|
|
|
|
|
|
It is legal and common to pass a pointer to a derived object when a pointer to a base object is expected. What happens when that pointer to a derived subject is deleted? If the destructor is virtual, as it should be, the right thing happensthe derived class's destructor is called. Because the derived class's destructor will automatically invoke the base class's destructor, the entire object will be properly destroyed. |
|
|
|
|
|
|
|
|
The rule of thumb is this: If any of the functions in your class are virtual, the destructor should be virtual as well. |
|
|
|
|
|
|
|
|
Virtual Copy Constructors |
|
|
|
|
|
|
|
|
As previously stated, no constructor can be virtual. Nonetheless, there are times when 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 it virtual. A clone method creates a new copy of the current object and returns that object. |
|
|
|
|
|
|
|
|
Because each derived class overrides the clone method, a copy of the derived class is created. Listing 17.4 illustrates how this is used. |
|
|
|
|
|
|
|
|
LISTING 17.4 A VIRTUAL COPY CONSTRUCTOR |
|
|
|
 |
|
|
|
|
1: //Listing 17.4 Virtual copy constructor
2:
3: #include <iostream.h>
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 |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|