tags:

views:

43

answers:

2

I have declared a class X in X.h as follows:

namespace Foo {
 class X{
....
};

}

In X.cc I would like to define the constructors, methods for X.

Do I need to enclose all my definitions inside namespace Foo {...} or prefix X as Foo::X:: for every method ?

It seems that sometimes I can just say (using namespace Foo) and not mention it again, i.e. just define methods as X::X() {...}

What is the correct approach here ?

+3  A: 

Any of the three approaches you suggest will work. Given:

namespace N {
    struct S {
        int F();
    };
}

You can put the definition in a namespace block:

namespace N {
    int S::f() { return 42; }
}

You can qualify the member name with the namespace name:

int N::S::f() { return 42; }

Or you can use a using directive (I'd not recommend this, though):

using namespace N;
int S::f() { return 42; }

Generally, I'd recommend against using a using directive. As for the other two (using a namespace block or qualifying the names), I don't think it really matters. I do both in my code.

James McNellis
`+1` for recommending against using directives. They lead to the dark side of the language.
sbi
@James, @sbi: I understand that we don't want to have 'using namespace N' in a .h file. Why is it bad to have it in the .cc file?
@user231536: It makes it harder to understand the source code because you don't know where names come from. It brings _all_ of the names into the enclosing namespace, which can cause a broad range of painful issues, one of the biggest of which is that you can unintentionally bring extra function overloads into consideration during overload resolution, which can result in the wrong function being called (or crazy compile-time errors).
James McNellis
A: 

No, you don't need to use namespace Foo {...} while defining your class. All your approaches are valid, but personally I'd prefer the following:

// In FOO.h
namespace FOO
{
 class A
 {
 public:
  A();
 };
}

And the implementation:

// In FOO.cpp
#include "Foo.h"
FOO::A::A()
{
 cout<<endl;
}
Jacob