Need to understand delete in destructors better?

Can someone explain to me why the two private variables width and height should be deleted in the destructor in the class Box? What if I did not delete the two variables in the destructor, what would happen?

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
#include <iostream>

class Box{
	long double *width;
	long double *height;
public:
	Box(long double, long double);
	~Box(void);

	int Area(void);
};

Box::Box(long double width_x, long double height_y){
	width = new long double;
	height = new long double;
	*width = width_x;
	*height = height_y;
}

Box::~Box(void){
	delete width;
	delete height;
}

int Box::Area(void){return(*width * *height);}

int main(){

	Box a(5,5);
	Box b(6,6);

	std::cout<<"Box 1 -> "<<a.Area()<<std::endl;
	std::cout<<"Box 2 -> "<<b.Area()<<std::endl;

	return 0;
}
Last edited on
The object of class Box will be destroyed but the memory that was allocated for width and height will not be freed. So every time when you will create and destroy objects of type Box unfreed memory will grow up and it can occur such a way that the next time you want to create a new object of type Box the system will respond that it has no enough free memory to allocate it for width and height of the object.
Last edited on
> why the two private variables width and height should be deleted in the destructor
Because the designer is an idiot.
1
2
3
4
5
class Box{
	long double width;
	long double height;
//...
}
Why would you call Bjarne Stroustrup an idiot? @ne555
@OTGC


I said numerous times that books of Stroustrup is not good to learn C++. Usually he uses program examples that demonstrate in fact how code should not be written. Stroustrup is a theoretic. He is not a strong programmer.
Last edited on
Well I have not really read his books. I learned this technique off the msdn section. Can you recommend me some books that are worth learnining c++?
If you use the copy constructor or assignment operator provided by the compiler, the pointer would be deleted twice. So the class is error prone.

In order to operate you'll need to dereference a pointer. http://www.youtube.com/watch?v=YQs6IC-vgmo
So the class is inefficient.

Also, it looks ugly.


Now consider the other approach.
The destructor, copy constructor and assignment operator are good enough, so you don't need to rewrite them.
In a container it would be layout contiguously, so less cache misses.
Topic archived. No new replies allowed.