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.
Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
To put it as an advice: Do not use "using namespace" (std or other) at file scope in header files. It is OK to use it in implementation files.
The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.
In an operating system, an example of namespace is a directory. Each name in a directory uniquely identifies one file or subdirectory. As a rule, names in a namespace cannot have more than one meaning; that is, different meanings cannot share the same name in the same namespace.
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.
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() {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With