Call to Destructor Function

Write your question here.

Why is the Destructor called between "mediumBox is smaller than bigBox" and "thatBox is equal to mediumBox"?


Constructor called.
Constructor called.
Constructor called.
Constructor called.
mediumBox is smaller than bigBox
Destructor called.
thatBox is equal to mediumBox
Destructor called.
Destructor called.
Destructor called.
Destructor called.
Press any key to continue . . .




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
//	Ex8_03.cpp
//	Exercising the overload 'less than' and equality operators
#include <iostream>			// For stream I/O
using std::cout;
using std::endl;

class CBox				// Class definition at global scope
{
public:
	//	Construction definition
	explicit CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0) :
		m_Length{ lv }, m_Width{ wv }, m_Height{ hv }
	{
		cout << "Constructor called." << endl;
	}

	//	Function to calculate the volume of a box
	double volume() const
	{
		return m_Length*m_Width*m_Height;
	}

	bool operator<(const CBox& aBox) const;	// Overloaded 'less than'

	//	Overloaded equality operator
	bool operator==(const CBox aBox) const
	{
		return this->volume() == aBox.volume();
	}

	//	Destructor definition
	~CBox()
	{
		cout << "Destructor called." << endl;
	}

private:
	double m_Length;
	double m_Width;
	double m_Height;
};

//	Operator function for 'less than' that
//	compares the volumes of CBox objects.
inline bool CBox::operator<(const CBox& aBox) const
{
	return this->volume() < aBox.volume();
}

int main()
{
	const CBox smallBox{ 4.0, 2.0, 1.0 };
	const CBox mediumBox{ 10.0, 4.0, 2.0 };
	CBox bigBox{ 30.0, 20.0, 40.0 };
	CBox thatBox{ 4.0, 2.0, 10.0 };

	if (mediumBox < smallBox)
		cout << "mediumBox is smaller than smallBox" << endl;

	if (mediumBox < bigBox)
		cout << "mediumBox is smaller than bigBox" << endl;
	else
		cout << "mediumBox is not smaller than bigBox" << endl;

	if (thatBox == mediumBox)
		cout << "thatBox is equal to mediumBox" << endl;
	else
		cout << "thatBox is not equal to mediumBox" << endl;

	return 0;
}
The CBox object is passed to operator== by value so that means aBox inside operator== is created as a new object using the copy constructor. aBox is a local variable inside operator== so when it goes out of scope, when the function returns, the destructor is called.
Thank you Peter87.

The error I made is that the CBox object should reference aBox so that the object is not copied. Line 26 should have been:

bool operator==(const CBox& aBox) const

If so, the destructor would not be called.

Thank you again.
Topic archived. No new replies allowed.