Search code examples
c++functionobjectreference-parameters

Initializing objects on the fly


I have a vector called players and a class called Player. And what I'm trying to do is to write:

players.push_back(Player(name, Weapon(bullets)));

So I want to be able to create players in a loop. But I see an error message says "no matching function for call Player::Player..."

Then I've changed that to:

Weapon w(bullets);
Player p(name, w);
players.push_back(p);

Here is my Player definition:

class Player {
public:
   Player(string &name, Weapon &weapon);
private
   string name;
   Weapon weapon;
}

I'm just trying to learn what is the difference between these definitions. And is this the right way to pass an object to an object constructor.

Note: These are not my actual class definitions. I'm just trying to learn something about object oriented programming in C++ with coding it. I mean I know that Weapon can be initialized in Player :)


Solution

  • Change constructor to:

    Player(const string &name, const Weapon &weapon);
    

    or:

    Player(const string &name, Weapon weapon);
    

    It's not valid C++ to initialize a reference with a temporary object, which is what you're doing when you use:

    Player(name, Weapon(bullets));
    

    it's legal to use a const reference though.

    EDIT: You should also pass name as a const reference or by value.