Hello, I'm having issues with pointers, specifically pointing towards a class named "game" containing a function to return a private variable with the class named "player". This class has specific functions designed to return private variables and the like.
The issue I'm having is that the Pointer itself returns NOTHING, however I am able to set variables accordingly, but they do not apply to what I am pointing at. I've tried creating a new solution, but the results are the same. I've completely given up. I believe I am doing everything correctly.
// NOTE: These classes would be declared in Header Files then defined in Source Files.
// Creating the "player" class. It will contain the variables our player will need.
class player{
public:
player(std::string nme = "Player");
std::string getNME();
void setNME(std::string nme);
private:
std::string NME;
};
player::player(std::string nme):
NME(nme)
{};
std::string player::getNME(){
return NME;
};
void player::setNME(std::string nme){
NME = nme;
};
// Creating the "game" class. It will contain our player.
class game{
public:
player getPly();
private:
player DefPly;
};
player game::getPly(){
return DefPly;
};
game RPG; // This will be used globally for other functions I may create.
int main(){
player * ptr = &RPG.getPly(); // Pointing to "DefPly"; the player held within the game "RPG".
// Before ...
std::cout << "Game: " << RPG.getPly().getNME() << std::endl;
std::cout << "Pointer: " << (*ptr).getNME() << std::endl;
(*ptr).setNME("Jon"); // Set the new name.
// After ...
std::cout << "Game: " << RPG.getPly().getNME() << std::endl;
std::cout << "Pointer: " << (*ptr).getNME() << std::endl;
// Pause
std::cout << "Press ENTER to continue." << std::endl;
std::cin.get();
return 0;
};
On line 35 you are not doing what you think you are doing. Your game::getPly() doesn't return DefPly, it returns a *copy*, so your pointer ends up pointing at a temporary variable that doesn't exist anymore.
You return a copy of DefPly in getPly() when you should be returning a reference (or just make the member public). Therefore, player * ptr = &RPG.getPly();
won't compile as you cannot take the address of a temporary.
Edit: too slow.
Also, you might not have noticed it, but you misspelled "name" and "player" several times.