referencing/setting string names to player objects

I am using a for loop to instantiate a number of player objects. Each object is is a different player in the game, and for the user's sake, I need to be able to know which player object is being referred to as the turns change during the game, therefore I need to be able to give each player object a name, such as Bruce, Alfred, or Harvey. I assumed I could use a setter to let the user input the players name when the constructor is called, but I can't seem to figure out how to do this. Can someone point me in the right direction? Below is what I have currently, but the cin in the setter does not work.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 class Player //player class to control chips and turns
{
public:
	static int chips;
	string name = "";

	Player() //player object constructor
	{
		chips = 3;
                name();
		
	}
	string name()
	{
		cin >> name;
		return name;
	}
Last edited on
You have a member variable and member function with the same name, which is probably the main issue you are having.

In general though, you will want to take input in the for loop and then pass the name to the constructor.
yea I saw that and fixed it. Sorry about that. So my constructor should take a string name as a parameter and then set name = name?
Yes, your constructor should look something like this:
7
8
9
10
11
Player(std::string const &name)
: name(name)
{
    //empty body
}
By the way, there's no need for the = "" on line 5, that is what the default constructor does already.
Last edited on
Topic archived. No new replies allowed.