Having trouble using string in a class

Hello, this is my first post in this forum.
I'm having trouble using string in class.In this program user inputs his player's name and race.In the output I want to show what he typed in 2 different lines.But the constructor does not seem to work.You can run the code uncommenting line 18.The string 'name' is not copying the string input by the user.
What am I doing wrong?
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <string>
using namespace std;

class player{
private:
    string name;
    string race;
public:
    player(string,string);
    string show_name();
    string show_race();
};
player::player(string n,string r)
{
    n=name;
    r=race;
    //cout<<name;
}
string player::show_name()
{
    return name;
}
string player::show_race()
{
    return race;
}

int main()
{
    string x,y;
    cout<<"Enter your player's name: ";
    getline(cin,x);

    cout<<"\nEnter your player's race: ";
    getline(cin,y);

    player p1(x,y);
    cout<<"name: "<<p1.show_name()<<endl;
    cout<<"race: "<<p1.show_race();

}
Last edited on
In your constructor you are not assigning values to your private member variables, but you are changingthe copies of input parameters.
name = n;
race = r;
Last edited on
Oops! That was my stupid mistake :D.
Thanks @abhishekm71
Topic archived. No new replies allowed.