I know that there are two ways to "store" an object in C++:// using a variable Car myCar; myCar.drive(); // using a pointer Car *myCarPointer = new Car(); myCarPointer->drive(); delete myCarPointer;
The second method is the way you would do it in C# or Java (minus the manual deletion), but both are valid in C++. The book I use (C++ Programming in Easy Steps) doesn't outline the difference other than that it looks like you can do something like this with a derived class:BaseClass *object = new DerivedClass();
In the context of a game, when would you want to use one over the other?
There are two big differences:
1) Things you allocate with new will be allocated on the heap (normally) (things created the first way ends up on the stack), the stack is normally faster but stack space is limited.
2) Multiple pointers can point to the same object (So if you are going to share one object between multiple other objects then pointers are good, allthough you could still allocate the object in question on the stack).
a few generic rules you can follow if you want:
* allocate small or short lived objects on the stack.
* allocate large objects on the heap
* don't use raw pointers (unique_ptr and shared_ptr are much better option in most cases),
so rather than
Class *obj = new Class()
shared_ptr<Class> obj(new Class())
no need to delete, its handled automatically and if you have multiple shared pointers to the same object(i made 2 in the example) the deletion will happen when all shared pointer have gone out of scope. unique_ptr works in the same way except it cannot be copied (like i did with the shared pointer) and thus doesn't have to count references (as you can only have one unique_ptr to each object that object gets deleted as soon as the unique_ptr goes out of scope)