I_4m_Z3r0
I_4m_Z3r0

Reputation: 1090

C++ - Explicit & Implicit Namespace Implementation Differences

I have a question about namespaces if someone can enlighten me :D

I don't know if the title is right, I hope so xD

Code in the ".cpp" file is called the Implementation of the Namespace and the code in ".h" file is called the Declaration of the Namespace? right? :/

Anyway, my Question is:

there is any difference by Explicit or Implicit Implementation of Namespace Members (in the ".cpp" file)?

I mean, let's suppose I have this namespace in "MyNamespace.h":

namespace MyNamespace {

    void fun_one(int a);

    void fun_two(int b);

}

There is any difference if in "MyNamespace.cpp" I do this (Implicit Implementation):

namespace MyNamespace {

    void fun_one(int a){
        // CODE HERE...
    }

    void fun_two(int b){
        // CODE HERE...
    }

}

Or this (Explicit Implementation):

void MyNamespace::fun_one(int a){
    // CODE HERE...
}

void MyNamespace::fun_two(int b){
    // CODE HERE...
}

?

Thanks you so much :D

Have a Nice day & a nice coding! (:

Upvotes: 1

Views: 742

Answers (2)

Useless
Useless

Reputation: 67802

... called the Implementation of the Namespace ... Declaration of the Namespace ...

Nope. Namespaces just ... scope names. They don't have a distinct declaration and implementation like a function.

What you have is the declaration of two functions, and then the definition of those two functions. The functions have names, and those names are scoped by the containing namespace, but nothing's really different from functions with names at file scope.

Which syntax you chooses to refer to those functions, with their scoped names - even in the function definition - is just that, syntactic. It only affects how the code looks, and has no effect on what it does.

Upvotes: 1

cigien
cigien

Reputation: 60268

In general, there is no difference between the 2 versions you have shown, and you can use whichever one you prefer.

For what it's worth, here's one case where it differs slightly:

namespace A 
{ 
  struct S{};
  S f();        // declare f
}

and then:

namespace A 
{
  S f() { return S{}; }   // define f, ok
}

is fine, but the following is not:

S A::f() { return S{}; }

since S is used before the introduction of namespace A. This can be fixed by doing:

A::S A::f() { return S{}; }

or

auto A::f() -> S { return S{}; }

Upvotes: 1

Related Questions