Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no namespace prepended for function when using namespace directive?

This c++ file...

namespace foo {
    class C {
        void m();
    };
    void f();
}

using namespace foo;

void C::m() {}
void f() {}

..Compiles to an object file with these symbols:

$ g++ foo.cpp  -c
$ nm foo.o  -C
000000000000000a T f()
0000000000000000 T foo::C::m()

Why does C::m()? get the namespace prepended, but not f()?

(I I instead of using namespace foo use namespace foo {...} then both names has foo prepended).

like image 524
Daniel Näslund Avatar asked May 27 '15 08:05

Daniel Näslund


1 Answers

In void C::m() {}, C::m is a qualified name, and such a definition always refers to something previously declared. The compiler looks up C, finds that C is actually foo::C, thanks to the using-directive, and it takes void C::m(){} as the definition of foo::C::m().

When you write void f() {}, that's a unqualified name, and it always declares the function in the current namespace, which is the global namespace.

like image 187
T.C. Avatar answered Nov 09 '22 04:11

T.C.