Lets suppose i have a class Player which has some meber function. One of them gives back the pointer of the object using the this keyword. Player* getPlayer() { return this;};
class Player
{
public:
Player(int id, string name, int score = 0) : pId(id), pName(name), pScore(score) { };
void rollDice();
int getId() { return pId; }
int getScore() { return pScore; }
string getName() { return pName; }
Player* getPlayer() { return this;};
private:
int pId;
std::string pName;
int pScore;
unsigned char playerDiceRolled;
Dice mDice;
};
I also have a class called Game which saves the information of any player in different vectors by using a function. One of this vectors saves the pointer of the object vector playerList;
class Game
{
public:
void Winer();
void addPlayer(Player A) ;
void updateScore();
vector<Player*> playerList;
vector<int> idList;
vector<string> nameList;
vector<size_t> scoreList;
};
void Game::addPlayer(Player A)
{
this->playerList.push_back(A.getPlayer());
this->idList.push_back(A.getId());
this->nameList.push_back(A.getName());
this->scoreList.push_back(A.getScore());
}
My question is can i take the pointer out of that vector and use it to call a function of that class and return the wright value.
i tried that but it doen't work
I can see that the other values of the Player are saved correctly but when i call a function using the pointer to get a value it returns null. For example
int main()
{
Game Game1;
Player A(0, "Player1");
Player B(1, "Player2");
Game1.addPlayer(A);
Game1.addPlayer(B);
cout << "Name is:" << Game1.nameList[1] << "\n";
cout << "Name is:" << Game1.playerList[1]->getName() << "\n";
return 0;
}
The cout gives the wright name of player for Game1.nameList[1] but NULL value for Game1.playerList[1]->getName()