Difference between vector<Name_of_class *name_of_variable> and vector<Name_of_class name_of_variable>

Hello there! :D

I think the title says it all, so does anyone who knows be willing to help me?
You can't have a variable name inside the template argument list.

1
2
vector<Name_of_class*> v1; // stores pointers
vector<Name_of_class> v2; // stores objects 

I found this that explains it a little more...


You can create the object on the stack like this:
1
2
Player player;
vectorOfGamers.push_back(player);    // <-- name of variable, not type 

Or you can even create a temporary object inline and push that (it gets copied when it's put in the vector):

vectorOfGamers.push_back(Player()); // <-- parentheses create a "temporary"

1
2
vector<Gamer> gamers;
gamers.push_back(Dealer());    // Doesn't work properly! 


Since when the dealer object is put into the vector, it gets copied as a Gamer object -- this means only the Gamer part is copied effectively "slicing" the object. You can use pointers, however, since then only the pointer would get copied, and the object is never sliced:

1
2
3
4
vector<Gamer*> gamers;
gamers.push_back(new Dealer());    // <-- Allocate on heap with `new`, since we
                                   // want the object to persist while it's
                                   // pointed to 

Topic archived. No new replies allowed.