Destructor in C++

Hello,

Why is it called destructive four times? I expected called destructor two times.
How can I fix it?

Thanks

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
#include <iostream>
using namespace std;

class Point
{
public:
	void input()
	{
		cin >> X;
		cin >> Y;
	}
	double X;
	double Y;
};

class Circle
{
	static int count;

private:
	double radius;
	Point center;


public:
	Circle(Point p, double r)
	{
		center = p;
		radius = r;
		count++;
	}
	~Circle()
	{
		count--;
		cout << "Radius is: " << radius << " ";
		cout << "X of Center is: " << center.X << " " << "Y of Center is : " << center.Y << endl;
		cout << "Count is: " << count << endl;
	}
	friend void Equal(Circle C1, Circle C2);

};

void Equal(Circle C1, Circle C2)
{
	if (C1.radius == C2.radius)
	{
		if ((C1.center.X == C1.center.Y) && (C2.center.X == C2.center.Y))
		{
			cout << "Two Circle is Equal"<<endl;
		}
	}
	else
	{
		cout << "Two Circle is NOT Equal"<<endl;
	}
}
int Circle::count = 0;

int main()
{
	Point P1;
	P1.input();

	Point P2;
	P2.input();

	Circle C1(P1, 5);
	Circle C2(P2, 14);

	Equal(C1,C2);

	return 0;
}
When I deleted a friend function(Equal) the above problem has been solved. but I need a friend function like that.
Why is it called destructive four times?

Because four Circle objects were created.

How can I fix it?

It's not broken.

But, if you want to reduce the number you create:
void Equal(Circle C1, Circle C2)
This function receives a COPY of each parameter. A WHOLE NEW Circle object. So two extra Circle objects are created, and passed to this function.

Pass by reference, void Equal(Circle& C1, Circle& C2) , and you won't make copies; the function will use the originals.
Last edited on
Just to follow up what Repeater correctly said:
Logic in your destructor is for cleaning up internal resources. The whole point is that it's hidden to the user if everything goes right. Unless for debugging purposes, you shouldn't put displaying/printing logic in your destructor. (In this particular case, you shouldn't even need to define a destructor, because your class doesn't use any unmanaged resources).

If you want to display information about your object, make a print function, or overload the << operator.

I know this might just be a contrived learning exercise, but I think it's good to point out.
Last edited on
Topic archived. No new replies allowed.