Creating and naming new class instances with a for loop

So I am a little confused about how classes work still. I need to create several Player classes when passed in a list of player names

I thought about looping through the list of names and making an instance of player for each one using:

1
2
3
4
5
6
7
8
  Blackjack(char *names[], int numPlayers){

    for(int i = 0; i < numPlayers; i++){ //loop through using number of players
      Player i; //create player
      i.m_playerName = names[i]; //set player name to array element
      i.m_playerFunds = 100; //set players default funds
    }
  }


but I figured that would essentially keep trying to make one Player just named "i" instead of what I actually wanted. I thought about passing in an array to have the prototype look something like

Blackjack(char *names[], int numPlayers, char playerList[])

however, I am not allowed to change the blackjack header. Does anyone have advice on how I would go about doing this?
Is this a constructor? Meaning, this is in a class? You should store each new player in a container in your class. I recommend std::vector but seeing as you are not even using std::string I will assume you're not allowed to or haven't been taught to, which is backwards.
It is a constructor within the Blackjack class

We are using vectors, but since we are not allowed to make changes to the header (cannot pass in anything aside from what is already passed in) how would I call the vector?
You don't "call" objects like vectors, you access them. Look in the class definition, what is the vector named? All you have to do is write that name in your constructor code and BAM you have access to it. Between lines 6 and 7 you would use .push_back(i).
so i have a vector declared

std::vector<Player> m_players;

i changed the original code so its now:

1
2
3
4
for(int i = 0; i < numPlayers; i++){ //loop through using number of players
      player[i] = names[i];
      Player m_player[i]; //create player
      m_player[i].m_playerName = names[i]; //set player name to array element 

where player is a vector and names is an array being passed in. My question now is with that last line, what exactly is the syntax supposed to be? I am trying to set the data element "m_playerName" to the i element of names array, and where "m_player[i]" is the name of the player class
the declaration is actually
std::vector<Player> players;
Let's start over.
1
2
3
4
5
6
7
8
  Blackjack(char *names[], int numPlayers){

    for(int i = 0; i < numPlayers; i++){ //loop through using number of players
      Player p; //create player
      p.m_playerName = names[i]; //set player name to array element
      p.m_playerFunds = 100; //set players default funds
    }
  }
This is your original code, but I renamed the player object to p so it didn't have the same name as the loop counter. You only need to add one line between lines 6 and 7 to achieve your goal.
Topic archived. No new replies allowed.