Learn C++ in 21 days - exercise 11.3: class destructors

According to the book the destructor for the Dog class and Mammal class should be called when the object "fido" loses scope. In the example they should be displayed after "Fido is 1 years old". When I run the program I see:

Mammal, constructor...
Dog, constructor...
Sound from mammal!
Shh. I'm asleep.
Wagging the tail...
Fido is 1 years old.

How come I don't see the destructors for fido?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

#include <iostream>
#include <limits>

using namespace std;

enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };

class Mammal
{
public:
		Mammal();
		~Mammal();
		
		int GetAge() const { return itsAge; }
		void SetAge(int age) { itsAge = age; }
		int GetWeight() const { return itsWeight; }
		void SetWeight(int weight) { itsWeight = weight; } 
		void Speak() const { cout << "Sound from a mammal!\n"; }
		void Sleep() const { cout << "Shhh. I'm asleep. \n"; }
		
protected:
          int itsAge;
          int itsWeight;
};

class Dog : public Mammal
{
public: 
		Dog();
		~Dog();
		
		BREED GetBreed() const { return itsBreed; }
		void SetBreed(BREED breed) { itsBreed = breed; }
		void WagTail() const { cout << "Wagging the tail...\n"; }
		void BegForFood() const { cout << "Begging for food..\n"; }
		
private:
		BREED itsBreed;
		
};	

Mammal::Mammal():
itsAge(1), 
itsWeight(5)
{
	cout << "Mammal, constructor...\n";
}

Mammal::~Mammal()
{ 
	cout << "Mammal, destructor...\n";
}

Dog::Dog():
itsBreed(GOLDEN)
{
	cout << "Dog, constructor...\n";
}

Dog::~Dog()
{
	cout << "Dog, destructor...\n";
}

int main()
{
	Dog fido;
	fido.Speak();
	fido.WagTail();
	cout << "Fido is " << fido.GetAge() << " years old.\n";
   	
    cout << "\n";
	
    std::cout << "Press ENTER to continue...";
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
    
    return 0;
	
}


fido isn't destroyed until the return statement is reached.
Try:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main()
{
    {
        Dog fido;
        fido.Speak();
        fido.WagTail();
        cout << "Fido is " << fido.GetAge() << " years old.\n";
    }
   	
    cout << "\n";
	
    std::cout << "Press ENTER to continue...";
    std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
    
    return 0;
	
}
Hit enter and there it is...
Thanks.
Topic archived. No new replies allowed.