Search code examples
c++scopescope-resolution-operator

Why do you use a Scope Resolution Operator when defining a class' method?


My question about the Scope Resolution Operator (::) is why do we use it in a CPP file to define the methods of a class? I'm more so asking about the SRO itself, rather than the relationship between CPP and Header files.


Solution

  • When you define a class:

    struct foo {
        void bar() {}
    };
    

    Then the full name of bar is ::foo::bar. The leading :: to refer to the global namespace can often be omitted. There is no bar in the global namespace, hence bar alone (or ::bar) does not name an entity and when you define the method out of line you need to tell what bar you mean:

     struct foo { 
           void bar();
     };
     struct baz {
           void bar();
     };
    
     void bar() {}    // this defines a completely unrelated free function called bar
    
     void foo::bar() {} // defines foo::bar
     void baz::bar() {} // defines baz::bar
    

    You need the scope resolution operator to state which method you want to define.

    For more details I refer you to https://en.cppreference.com/w/cpp/language/lookup