tags:

views:

97

answers:

3

Do I have to put code from .cpp in a namespace from corresponding .h or it's enough to just write using declaration?

//file .h
namespace a
{
/*interface*/
class my
{
};
}

//file .cpp

using a::my; // Can I just write in this file this declaration and
             // after that start to write implementation, or
             // should I write:

namespace a //everything in a namespace now
{
//Implementation goes here
}

Thanks.

+1  A: 

If I understood the question correctly, you can have just using a::my and then just implement the methods, like

using a::my;

void my::doSomething() {}
luiscubal
A: 

You can do it. But, should you?

It's an uncommon practice, and it will probably lead to a proliferation of using a::Type; for every type from namespace 'a' used in the .cc file. Whether that is a good thing is for you to decide, but I'd vote against it :)

Stephen
You can also use `using namespace a;` and implement the code without needing to have a big namespace a{} in the code. Namespace declarations are for headers.
luiscubal
+3  A: 

I consider more appropriate to surround all the code that is meant to be in the namespace within a namespace a { ... } block, as that is semantically what you are doing: you are defining elements within the a namespace. But if you are only defining members then both things will work.

When the compiler finds void my::foo(), it will try to determine what my is, and it will find the using a::my, resolve my from that and understand that you are defining the a::my::foo method.

On the other hand this approach will fail if you are using free functions:

// header
namespace a {
   class my { // ... 
   };
   std::ostream & operator<<( std::ostream& o, my const & m );
}
// cpp
using a::my;
using std;
ostream & operator<<( ostream & o, my const & m ) {
   //....
}

The compiler will happily translate the above code into a program, but what it is actually doing is declaring std::ostream& a::operator<<( std::ostream&, a::my const & ) in the header file --without implementation--, and defining std::ostream& ::operator<<( std::ostream &, a::my const & ) in the cpp file, which is a different function. Using Koening lookup, whenever the compiler sees cout << obj with obj of type a::my, the compiler will look in the enclosing namespaces of cout and my (std, and a) and will find that there is an a::operator<< declared but never defined in namespace a. It will compile but not link your code.

David Rodríguez - dribeas
+1. What's in the namespace is in the `namespace{}`. Things like this don't demand indentation so there is really no trouble.
Potatoswatter