Sign in to follow this  

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

This topic is 1421 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

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

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

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

This topic is 1421 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this