Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

JesseJenson

Newbie C++ Question

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

Hey Guys, I''m pretty much just starting with C++, and I''m working with classes. I was wondering, when I start on a game, do I have to use my classes/data in free space, or can I use them in the stack? Thanks a bunch! -Jesse

Share this post


Link to post
Share on other sites
Advertisement
Classes are generally allocated from the heap, rather than on the stack; However it really depends on how you''re going to use them. Ex: string classes are usually ok to put on the stack, as long as you don''t try to pass them as return values.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Can somebody explain the difference between
putting variables (?) on the heap and stack?

If I declare a private string or int in a class
where is that being stored?

Thanks..

Share this post


Link to post
Share on other sites
When you declare something in a class, it''s allocated with the instance of the class. If you declare something as a local variable it''s allocated on the stack, if you create it using the new keyword it''s created on the heap.
ex:
int a;
allocates an int on the stack.
int * a = new int;
allocates an int from the heap. (and also a pointer to an int on the stack.)

Share this post


Link to post
Share on other sites
If you use new to allocate memory for a certain object (be it builtin or of class type), then the amount of memory needed for that object will be allocated on the heap. The memory will only be reclaimed when a corresponding delete is used.

If you have local variables in a function, the storage needed for that variable is allocated on the stack. The memory is reclaimed when the object goes out of scope (eg when the function ends).

The thing to keep in mind is that when you return a reference to or address from local variable in a function, the memory that pointer/reference addresses is reclaimed when the function exits.

OTOH, if you use new, the storage remains when the functions exits, but you have to delete the memory or else you get a memory leak.

Erik

Share this post


Link to post
Share on other sites

  • 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!