Is it good practice to prefix a function definition with a namespace in CPP files?

// classone.h
namespace NameOne
{

class ClassOne
{
public:
    ...
    void FuncOne();
    ...
};

}

// *** Method 1 *** 
// classone.cpp
namespace NameOne // always define member functions inside the namespace
{

void ClassOne::FuncOne()
{ ... }

}

// *** Method 2 *** 
// classone.cpp
void NameOne::ClassOne::FuncOne() // always prefix the namespace
{ ... }

      

Question I have seen two methods for handling namespace in CPP files. Which method is best practice on a large project (i.e. Method 1 or Method 2)

thank

+3


source to share


6 answers


If it's not in the header file, it doesn't matter as long as you're consistent. I personally prefer the first method as the namespace is not that important when you read the function name.



+4


source


This is the only situation where I am using using namespace X

.
I think it's okay to use it (but I'm still thinking about it), but want to hear different points of view.

In the Bar.cpp file

// Bar in namespace Foo
#include "Bar.h"

// Only do this for the class I am defining
using namespace Foo;
Bar::Bar()
{
}
void Bar::stop()
{
}
// etc

      



I experimented with:

// Bar in namespace Foo
#include "Bar.h"

// Only do this for the class I am defining
using Foo::Bar;
Bar::Bar()
{
}
void Bar::stop()
{
}
// etc

      

+1


source


I think it very much depends on your personal preference, and furthermore, depending on what has already been used in the codebase, you write the code.

0


source


I prefer to add using namespace NameOne

. Method 1 increases the indentation, method 2 makes the declaration longer, but this is just a personal opinion. Just be consistent in your code (and code base).

0


source


I'm sure I remember reading around the namespaces that were introduced in C ++ that Method 2 is the best approach and is definitely preferred over Method 1, and this is what I have always used.

0


source


The reason for using a namespace is usually to collect your classes / methods in a group / package with a sequential function so that they don't match definitions (both literally and functionally) in other libraries or namespaces.

So I prefer using namespace Foo

in cpp files because most of the time I belong to different classes in the same namespace. If I need to use a class from a different namespace, I definitely use the suffix Foo2::

. It keeps the distance between the implemented namespace and others.

0


source







All Articles