c++ - Unable to change private variable's content -


main.cpp :

#include <iostream> #include <string> #include "players.h" using namespace std;  int main () {     cout << "**** welcome leviathan's first tictactoe game! ****\n\n";     players getnamesobject;     players printnamesobject;     getnamesobject.getplayersnames();     printnamesobject.printplayersnames();  } 

players.h:

#ifndef players_h #define players_h   class players {     public:         void getplayersnames();         void printplayersnames();     private:         std::string _player1name;         std::string _player2name; };  #endif // players_h 

players.cpp :

#include <iostream> #include <string> #include "players.h" using namespace std;  void players::getplayersnames() {     string p1,p2;     cout << "enter player 1 name : ";     cin >> p1;     cout << "\nenter player 2 name : ";     cin >> p2;     _player1name = p1;     _player2name = p2; }  void players::printplayersnames() {     cout << "alright " << _player1name << " , " << _player2name <<", game has begun!\n\n"; } 

when run this, , enter 2 names, _player1name , _player2name variables don't changed. i've tried setting them string manually , printed normally. can explain what's wrong here? seems getplayernames function can't change private variables?

it's because have two different objects!

one set member variables in (through getplayersnames function), , unrelated object use print different set of variables.

you should have single object, , call getplayersnames , printplayersnames on single object. like

players playersobject; playersobject.getplayersnames(); playersobject.printplayersnames(); 

each instance of players object create have own set of member variables tied single object, member variables not shared between objects (unless make them static).


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -