Changing object variable

Hey guys, im new to the forum. I just wanted to ask something about this code.
I want to change the name of the Player J1 inside the main, but its being impossible for me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
using namespace std;
class Player
{
public:
    Player (string _name) : name (_name) {}
    ~Player(){}
    string getname() {return name;}
    void setname (string _name) {_name=name;}
private:
    string name;
};

int main()
{
    Player J1 ( "Player 1");
    Player *pJ1 (NULL);
    pJ1=&J1;
    cout << "Current name: " << J1.getname() <<endl;
    pJ1->getname()="JAMES";
    cout <<"Name pJ1: " << pJ1->getname() << endl;
    J1.getname()="JAMES";
    cout <<"Name J1: " << J1.getname()<< endl;
    return 0;
}

Always prints "Player 1".. and i want to change the name. the only way i can change the name is doing string name public, but i want string name to be private. Help? thanks
Last edited on
Use setname to change the name.

 
J1.setname("JAMES");
Thank you, i changed the get for the set like you said, and also there was an error on the declaration of the class player. Now it works. It should be:

 
void setname (string _name) {name=_name;}
your code will work too if you return the name by reference

string& getname() {return name;}

Last edited on
Topic archived. No new replies allowed.