Problem(s) of using namespace directive

I see two drawbacks when using the “using namespace” directive.

First, if two namespaces expose the same function/object name, using it without namespace identifier is ambiguous. I’m not sure how the compiler handles this: if it blocks with an error, or compile it anyway (and good luck at runtime - which item does it use from the two namespaces?).

Second: code readability. Without namespace qualifier, a reader cannot be sure what was the actual object/function being used, making it harder to understand and maintain the code.

1 Like

I’m not sure how the compiler handles this: if it blocks with an error, or compile it anyway (and good luck at runtime - which item does it use from the two namespaces?).

This sounds like something you can find out yourself, and learn about making namespaces too!

  1. What happens if you write two methods with the same name? (Two ‘main’ methods, for example)

  2. What happens if you write two methods with the same name, in two namespaces, where one namespace is ‘used’ and the other isn’t?

  3. What happens if both namespaces are used?

  4. Does the compiler complain only when those methods are called, or does it detect the conflict and warn/error even if they are unused?

These are all questions for myself, too, as I don’t know the answers. At this point in the course, we haven’t been taught how to make namespaces, but I’m sure we will soon and we can revisit these questions later. Or, look up how to make namespaces online! I know it’s very simple from previous experience, but haven’t done it in a while.

So I just found these answers out. Rather than give away the solution, here are the pieces you need to find the answers yourself;

To make a namespace, simply use the following pattern:

namespace my_namespace_name
{
    // We've made a namespace! That was easy.
    void Hello() // 'void' return type means, return nothing.
    {
        cout << "Hello from my_namespace_name!" << endl;
    }
}

using namespace my_namespace_name;

And, call ‘Hello’ with,

my_namespace_name::Hello(); // (Or, simply Hello() if using the namespace)

NB. the ‘using’ directive must be after the namespace definition, or it will not know about it. Likewise, the main() method where you call these functions must be after these definitions, for the same reason.

1 Like

@Jon_Chapman thanks for your replies and hints! Unfortunately I had to pause the course for a while, I got back just today. I’ll workout the issues about namespaces (now I didn’t resist to get my fingers wet with Unreal Engine itself).

Thanks again, cheers and have fun!

Fabio

Privacy & Terms