In a C++ class, we can write our members in either of two styles. We can put them inside of a namespace block, or we can fully qualify each.
Is there any reason to prefer one style over the other?
Header file looks like this (bar.h):
namespace foo
{
class Bar
{
public:
Bar();
int Beans();
};
}
Style 1 (bar.cpp) - Declarations within namespace block:
#include "bar.h"
namespace foo
{
Bar::Bar()
{
}
int Bar::Beans()
{
}
}
Style 2 (bar.cpp) - Fully qualified declarations:
#include "bar.h"
foo::Bar::Bar()
{
}
int foo::Bar::Beans()
{
}
So my question, again, is: is there any reason to prefer one style over the other?
Here's a possible answer that was posted by James Kanze in answer to another similar question. (edit: note from the comment thread, this only applies to non-member functions).
Prefer the fully qualified form (style 2).
Functions written in this style are explicitly a definition, not a declaration.
That is to say, using Style 2, if you accidentally define a function with incorrect arguments, you'll get a compiler error alerting you to that fact.
Using Style 1, if you define a function with incorrect arguments it will define a different function. It will compile fine, but you'll get a linker error explaining that the method is not defined. This will probably be harder to diagnose than the compiler error resulting from Style 2.