Home > Enterprise >  In c Why and how classname::member syntax can be used for an instance member?
In c Why and how classname::member syntax can be used for an instance member?

Time:10-23

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

CodePudding user response:

According to the C 17 Standard (6.4.3 Qualified name lookup)

1 The name of a class or namespace member or enumerator can be referred to after the :: scope resolution operator (8.1) applied to a nested-name-specifier that denotes its class, namespace, or enumeration. If a :: scope resolution operator in a nested-name-specifier is not preceded by a decltype-specifier, lookup of the name preceding that :: considers only namespaces, types, and templates whose specializations are types. If the name found does not designate a namespace or a class, enumeration, or dependent type, the program is ill-formed.

CodePudding user response:

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:

  1. name is a unqualified name while Human::name is a qualified name.

  2. For name unqualified lookup will happen while for Human::name qualified lookup will happen.


The similarity between the two is that:

  1. Both at the end of the day refer to the same non-static data member.
  • Related