Accessing member variables through a function.

In short: I would like to make a function that takes in an instance of a class and accesses it's public variables within the function.

ie

SetName(Player Mchr, string s)
{
Mchr.name = s;
}

I'm not sure what I'm doing wrong, but it seems like the function can't access Mchr.name through Mchr. I'll post my code below in case it's a semantic issue instead of a philosophical one.


#include <iostream>
#include <string>
#include "File.h"

using namespace std;

int main()
{
string player_name;
cin>> player_name;
Player Mchr;
SetName(Mchr, player_name);
cout<< Mchr.name;


int end;
cin>> end;

return 0;
}



and in "File.h"



#ifndef __Class_Function_Test__File__
#define __Class_Function_Test__File__

#include <iostream>
#include <string>
using namespace std;

class Player
{
public:
Player()
{
name= "N/A";
}
string name;
};

void SetName(Player Target, string in_name)
{
Target.name= in_name;
}

#endif

Passing the instance by reference should do the trick.
1
2
3
4
void SetName(Player & Mchr, string s)
{
    Mchr.name = s;
}

However, making name private and SetName a member function would be preferred.
1
2
3
4
5
6
7
class Player {
    string name;
public:
    void SetName( const & string s ) {
        name = s;
    }
};
Last edited on
> void SetName( Player Mchr, string s )

This is pass by value; the function modifies a copy of the object.

Pass by reference instead: void SetName( Player& Mchr, string s )
Great! Thanks!
Topic archived. No new replies allowed.