Jump to content
  • Advertisement
Sign in to follow this  
h0wser

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

This topic is 2066 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Advertisement

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.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!