Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 935
pocoa Avatar asked Feb 20 '26 05:02

pocoa


2 Answers

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.

like image 107
Andreas Brinck Avatar answered Feb 21 '26 17:02

Andreas Brinck


You are passing a temporary (Weapon(bullets)) to the Player constructor, which takes a Weapon &. But since you're not allowed to make a reference to a temporary, this fails.

You are, however, allowed to make a const reference to a temporary. Thus, redeclare your constructor as follows:

   Player(string const &name, Weapon const &weapon);
like image 45
Thomas Avatar answered Feb 21 '26 18:02

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!