Vagabond
Vagabond

Reputation: 167

Usage of namespaces in c++

Can we use namespaces like in below snippet? The code compiles in both gcc and msvc, leaving me confused about namespace usage.

In f1.h:

namespace My
{
 void foo();
}

In f1.cpp `

void My::foo()
{
}

I thought that the function should be defined as:

namespace My {
void foo() {}
}

Can anyone kindly explain?

Thanks

Upvotes: 2

Views: 399

Answers (5)

Yonathan
Yonathan

Reputation: 1313

It's the same as doing: using std namespace; on top and just doing cout instead of doing std::cout. Both will work and both are valid, but you do have to think about how to use them. There are pro's and cons.

Upvotes: 0

Robben_Ford_Fan_boy
Robben_Ford_Fan_boy

Reputation: 8720

I like that this is allowed:

namespace My
{
 void foo();
}

As it means that if a utility method is quite long it does not clutter up the header file. That way it is more obvious what methods are provided in the namespace.

I know this may be a null point with the expressiveness of modern IDEs but it still helps to have clean header files.

Upvotes: 0

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506847

It's legal to define namespace members outside of their namespace as long as their name is prefixed with the name of their namespace, and the definition actually occurs in a namespace that encloses it. It can't happen in a namespace that's nested inside the member namespace.

namespace A { void f(); }
void A::f() { } // prefix with "A::"

namespace B { }
void B::f() { } // invalid! not declared in B!

namespace C { void f(); }
namespace D { void C::f() { } } // invalid! D doesn't enclose C

namespace E {
  void f();
  namespace F {
    void E::f() { } // invalid! F is nested inside E!
  }
}

It's the same stuff as for class members, where you can also define functions outside of their class, as long as you prefix the names with the name of the class. However as for classes, namespace members must be first declared in their respective namespace before they can be defined outside out it.

Upvotes: 8

ufukgun
ufukgun

Reputation: 7209

both is true

you can set namespace globally or for each function

namespace My {
//in this are functions are in "My" namespace
}

namespace Your {
//in this are functions are in "Your" namespace
}

My::foo() {}
My::bar() {}
Your::foo() {}

if you dont want write "My::" at the beginning of each function, you write it as first one. the second is useful when there are more than one namespace

Upvotes: 0

Goz
Goz

Reputation: 62323

Yeah thats fine. By doing the "My::" you are indicating you are using the "My" namespace.

The same way as you can declare an STL vector as "std::vector< int >" ...

Upvotes: 0

Related Questions