Why don't I need to use a namespace?

So, I have the following functions:

GraSys::CRectangle GraSys::CPlane::boundingBox(std::string type, std::string color)
{
   CRectangle myObject = CRectangle(color);
   return myObject;
}

      

Since boundingBox is part of the GraSys namespace and I have to use it to declare this function, why don't I need to do it inside a function? Why can I just use? why does it allow me to compile the problem?

CRectangle myObject = CRectangle(color);

      

insted of:

GraSys::CRectangle myObject = GraSys::CRectangle(color);

      

Hope my question is not confusing.

+3


source to share


3 answers


You are implementing a function declared in the GrasSys namespace. When you are in this function, you are using the declaring namespace.

For clarity, consider:



namespace GraSys {
    class CRectangle { ... };
    class CPlane {
        ... boundingBox(...); ...
    }
    void example(...) { ... };
}

      

When you implement boundingBox, you will be in the namespace declared during the function declaration, which is GraSys. CRectangle is declared inside GraSys, so you can use it directly. Also note that you can also call functions directly, so in the above code, you can call the example directly in your boundingBox implementation.

+2


source


This is called unqualified name lookup. You can read the full search rules in the C ++ standard section, 3.4.1

or in a more readable form here .

Here's an example from the standard that might be better than detailed explanations:



namespace A {
    namespace N {
        void f();
    }
}

void A::N::f() {
    i = 5;
    // The following scopes are searched for a declaration of i:
    // 1) outermost block scope of A::N::f, before the use of i
    // 2) scope of namespace N
    // 3) scope of namespace A
    // 4) global scope, before the definition of A::N::f
}

      

+1


source


using namespace

is similar to adding a namespace to a global namespace (such as a namespace). if you do this, from now on the compiler will look for every character in all used namespaces.

Only in case of ambiguity (means a symbol with the same name declared in the 2 used namespaces, you will have to use the namespace.

namespace A{
   void f();
   void g();
}    

namespace B{
    void g();
}

using namespace A;
using namespace B;

A::f(); //always work
f(); //work since it is the only symbol named f

A::g();//always work
B::g();//always work
g();// error since g is ambiguous.

      

0


source







All Articles