Wondering how heap allocation works with classes[c++]

Started by
3 comments, last by ryt 10 years, 1 month ago

I come from C# so having to manually manage memory is new to me.

I was wondering what happens if I have a class Foo that holds another object Bar and I instantiate foo on the heap; where does bar end up?

In code:


class Bar {
	
	public:
		Bar(){}
};

class Foo {

	Foo()
	 : bar() 
	{

	}

	private:
		Bar bar;
};

int main()
{
	Foo* foo = new Foo();

	delete foo;

	return 0;
}

Is bar also placed on the heap? and in that case do I need to manually release bar or is it freed automatically by Foo?

“Life isn't about finding yourself. Life is about creating yourself.” ? George Bernard Shaw
Advertisement

The bar variable is a part of the Foo class, contained within it (Foo's memory allocation is big enough to contain this Bar instance inside itself -- sizeof(Foo) >= sizeof(Bar)).

Wherever a Foo is allocated, then m_bar is created inside that allocation. When a Foo is constructed, the m_bar variable is also constructed automatically. Likewise, when a Foo is destructed, the m_bar variable is also automatically destructed.

m_bar never needs to be free'd/deleted, because it was not created using malloc/new.

I think your confusion comes from the fact that there are "reference types" (class) and "value types" (struct) in C#. In C++, there is no such distinction. Everything is a value type; if you want to have references or pointers, this must be specified explicitly.

So if you add a member of type Bar to class Foo, and Bar needs 32 bytes, the size of Foo grows by 32 bytes (assuming no padding bytes). There is no pointer or reference in Foo that points to an instance of Bar.

Those are both good explanations, thanks a lot for helping me clear this out guys :)

“Life isn't about finding yourself. Life is about creating yourself.” ? George Bernard Shaw

You do not need to free Bar since it is in declared in it and when you free Foo it gets removed automatically as Hodgman sad.

If you create Bar in Main() it gets created on stack in this function and its removed automatically as you leave the function since stack on this function no longer exists. Similar is with the heap. But you need to remove it manually and when you do its all contents is removed.

This topic is closed to new replies.

Advertisement