Memory Management

Hello, I was wondering something about classes. Let's say that I have a class like such:

1
2
3
4
5
6
7
8
9
10
class Cfoo
{
public:
	int *bar;

	Cfoo(int bar)
	{
		this->bar = new int(bar);
	}
};


Then I initialized the class like such:

Cfoo *foo = new Cfoo(10);

Then if I deleted the class like such:

delete foo; foo = 0;

So my entire code looks like thus:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

class Cfoo
{
public:
	int *bar;

	Cfoo(int bar)
	{
		this->bar = new int(bar);
	}
};

int main()
{
	Cfoo *foo = new Cfoo(10);

	delete foo; foo = 0;

	return 0;
}

Does, C++ delete the 'bar' variable as well? Or do I have to make a deconstructor something like this:

1
2
3
4
~Cfoo()
{
	delete bar; bar = 0;
}
Last edited on
Though your code is full of errors nevertheless the destructor will free only the memory occupied by the class object. Memory pointed by data member bar will not be free.
Sorry, about the errors. I typed too fast, and I have been programming in JavaScript for the past couple of weeks. I have corrected the errors.

So, Cfoo::bar will not be released when the object is deleted?
Visualize:

foo -> Cfoo object on the heap
           Cfoo::bar                      -> int on the heap

delete foo; foo = 0;

foo -> 0
                  Cfoo object deleted
                                                   int still on the heap


When you call delete, only the object pointed to is deleted. If that object happens to have pointers to other locations on the heap, you'll have to take care of that in the object's destructor (best location for clean up).
This holds for both allocated objects and stack objects, i.e. even if foo was the object and not a pointer, you still need that destructor to clean up resources.
Ah, okay! Thanks for the visualization. That helped alot. I wasn't sure if C++ would take care of the members in the class. Since it doesn't, (which I guess is part of the point of the pointers) I have to release the memory myself.
Topic archived. No new replies allowed.