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::nameis a qualified name that refers to(or names) the non-static data membername. For qualified names likeHuman::name, qualified lookup happens which will find the data membername.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 namedname. And so you could have just usedname(instead ofHuman::name) as it will also refer to the same non-static data member.Basically the main difference between
nameandHuman::nameare that:nameis a unqualified name whileHuman::nameis a qualified name.For
nameunqualified lookup will happen while forHuman::namequalified lookup will happen.The similarity between the two is that: