Class function question

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


class OneClass{
public:
void setName(string a, string b){
a = b;
}
string getName(){
return name;
}
private:
string name;
};


int main(){

OneClass obj1;
obj1.setName("name","is you");
cout << obj1.getName() << endl;

return 0;
}

My question is:
can i in "obj1.setName("name","is you"); the "name" actualy being used as the
"string name" from the class "OneClass" that is private:
so in "cout << obj1.getName() << endl; id get the "is you".
you'll need a point to member-funciton like this:
1
2
3
4
typedef void (OneClass::*pointer)(string, string);
OneClass obj1;
pointer MyPointer = &obj1::setName;
(obj1.MyPointer)();
No, you can't use the content of a string to specify the name of the variable, for the simple reason that a variable does not keep it's name once compiled. The variable is asssociated to some memory, and references to the variable become references to the address of that memory.
To do something like that, you yould need to use something to map the attribute name to the address of the variable to be modified: like STL map for example.

Why aren't you just using
1
2
3
void setName(string b){
name = b;
}
in your case? You are allowed to access a private attribute in the body of the public method of the same class
Topic archived. No new replies allowed.