Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using namespace for function-member definition

I have the following class definition in .h file:

namespace N {
    struct S {
        S(); // no definition for member here    
    };
}

And I would like to write definition for class constructor (member in general) in .cpp file. I consider the following two cases:

  1. namespace N {
        S::S() { /* definition */ }  
    }
    
  2. using namespace N;
    S::S() { /* definition */ }  
    

I'm slightly confused why the second is working at all, because never saw this way definition until today. Why the second is working? Some citing from the Standard would be appreciated.

What are the nuances of using one approach instead of the other? Should I prefer the first or the second form?

like image 243
αλεχολυτ Avatar asked Sep 22 '26 11:09

αλεχολυτ


1 Answers

The reason (2) works is because of these two:

  1. [class.mfct]/4

    If the definition of a member function is lexically outside its class definition, the member function name shall be qualified by its class name using the ​::​ operator.

  2. [namespace.udir]/2 (emphasis mine)

    A using-directive specifies that the names in the nominated namespace can be used in the scope in which the using-directive appears after the using-directive. During unqualified name lookup, the names appear as if they were declared in the nearest enclosing namespace which contains both the using-directive and the nominated namespace. [ Note: In this context, “contains” means “contains directly or indirectly”.  — end note ]

The directive simply lets you name S for the :: operator as if you were inside the N namespace (as you are in (1)). But I wouldn't do that. Scoping is good. Definitions should be scoped too.

like image 66
StoryTeller - Unslander Monica Avatar answered Sep 25 '26 01:09

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!