class Human {
public:
Human(string name);
string getName() {
return Human::name;
}
void setName(string name) {
Human::name = name ;
}
private:
string name;
};
Human::name in getName and setName funcs. work perfectly although name is not a static variable.
Why is this happening ?
As far as I know "::" is used to acces functions or static members of a class.
I thought correct usage in getName would be return this -> name or return name.
And even, when generated auto setter function in Clion, setter function uses Human::name not this -> name
I'm coming from java background and in java classname.X (which resembles classname::X in c++) was only used for static members or functions of a class. That is why I am confused
First things first, you're missing a return statement inside setName
, so the program will have undefined behavior.
Now, Human::name
is a qualified name that refers to(or names) the non-static data member name
. For qualified names like Human::name
, qualified lookup happens which will find the data member name
.
On the other hand, just name
(without any qualification) is an unqualified name and so for it, unqualified lookup will happen which will also find the data member named name
. And so you could have just used name
(instead of Human::name
) as it will also refer to the same non-static data member.
Basically the main difference between name
and Human::name
are that:
name
is a unqualified name while Human::name
is a qualified name.
For name
unqualified lookup will happen while for Human::name
qualified lookup will happen.
The similarity between the two is that: