Program:

``````#include <iostream>

using namespace std;

class Rectangle {
float len;
float bre;

public:

Rectangle() {cout << "Rectangle constructed!" << endl; len=0; bre=0;}
~Rectangle() {cout << "Rectangle destructed!" << endl;}

void setL(float L) {len=L;}
void setB(float B) {bre=B;}

friend float area(Rectangle rect);
};

float area(Rectangle rect) {
return rect.len*rect.bre;
}

int main(void) {
float _L, _B;
Rectangle obj;

cout << "Enter the length and breadth of the rectangle: ";
cin >> _L >> _B;
obj.setL(_L);
obj.setB(_B);

cout << "The area of the Rectangle = " << area(obj) << "." << endl;

return 0;
}
``````

Output:

``````Rectangle constructed!
Enter the length and breadth of the rectangle: 1 3
The area of the Rectangle = 3.
Rectangle destructed!
Rectangle destructed!
``````

Why is "Rectangle destructed!" printed twice?

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by JasonHippy

Because the object is passed by value to the area function, meaning that another, temporary rectangle object is created and passed to the area function. When the area function is done, that temporary is destroyed. Afterwards, when the main function ends, the obj is destroyed.

Try changing the area function to pass by reference as so:

``````float area(const Rectangle& rect);
``````

and similarly for the friend declaration of it. This should eliminate the temporary and result in only a single destruction.

Another test you can do is to create a copy-constructor as so:

``````Rectangle(const Rectangle& lhs) {cout << "Rectangle copy-constructed!" << endl; len = lhs.len; bre = lhs.bre; }
``````
Thanks :)

Because you're passing rect by value into the area function, a copy of the Rectangle object is created inside the function using the default copy constructor (which will be automatically created by the compiler as you haven't created a copy constructor).
The first call to the Rectangle destructor occurs when it drops out of scope after your area function returns, destroying the local copy of the Rectangle.
The second call to the Rectangle destructor occurs when 'rect' drops out of scope when your main() function ends.
To avoid a local copy of the passed-in Rectangle being made, you could set the area function up to take a const reference to a Rectangle object instead.

Hope this clears things up for you!

edit: Damn, beaten to the punch again! Very quick as ever Mike!

Edited by JasonHippy: Mike is a ninja!