SFML community forums

Help => General => Topic started by: jonathansty on August 03, 2015, 03:16:05 pm

Title: Question regarding the creation of objects.
Post by: jonathansty on August 03, 2015, 03:16:05 pm
Hello everyone,

Why do you use:
sf::Sprite sprite

and not
sf::Sprite* sprite

What's the different and why should you use one over the other?
I know the first variable is created on the stack and the second one is a pointer to an object on the heap?
Isn't the stack limited so won't it be a problem once you start using lots of variables?
Title: Re: Question regarding the creation of objects.
Post by: eXpl0it3r on August 03, 2015, 03:33:24 pm
This is a basic C++ question and is not really related to SFML.
If you don't know when to use what, you might play around a bit longer with pure C++ and keep reading a good C++ book (https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), before starting to work more with SFML.

The first is a local variable created on the stack. The second is by itself just a pointer. The pointer can point to a variable on the stack as well as one on the heap.
You should work on the stack as much as possible and only create objects on the heap if they need to be dynamically created.
However if you do create a dynamic object, you should make sure to use RAII and smart pointers and not work with new/delete, that's "old" C++ and is hard to use properly. See also "Why RAII rocks" (http://www.bromeon.ch/articles/raii.html).
Title: Re: Question regarding the creation of objects.
Post by: zsbzsb on August 03, 2015, 03:40:29 pm
Another link that may help you out is this SO question: http://stackoverflow.com/questions/599308/proper-stack-and-heap-usage-in-c