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

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

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 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 on other sites

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

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.

• What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 14
• 14
• 45
• 22
• 27
• Forum Statistics

• Total Topics
634044
• Total Posts
3015213
×