0

Suppose I have the following files:

// SomeClass.h
namespace Example
{
    class SomeClass
    {
        ...
        SomeClass someFunction();
        ...
    };

}

// SomeClass.cpp
Example::SomeClass Example::SomeClass::SomeFunction()
{
    ...
}

Would there be any consequences to add "using namespace Example;" before the namespace in SomeClass.h to eliminate the need of adding the "Example::" scope operator to things in the Someclass.cpp file? Even if there are no conesequences, would this be considered bad coding practice?

The change would be as follows:

// SomeClass.h
using namespace Example;

namespace Example
{
    class SomeClass
    {
        ...
        SomeClass someFunction();
        ...
    };

}

// SomeClass.cpp
SomeClass SomeClass::SomeFunction()
{
    ...
}
3
  • 1
    I use that all the time in .cpp files. I haven't seen any downsides yet. However, I haven't used them in .h files. Keep in mind that you can't use using namesapce Example; before the namespace is introduced. Commented Nov 12, 2014 at 5:13
  • Didn't consider throwing that in the .cpp, thanks. Commented Nov 12, 2014 at 5:22
  • 1
    As R Sahu said, do not throw a using namespace in your header. It pollutes the global namespace of every file which includes it (not fun). Commented Nov 12, 2014 at 5:23

1 Answer 1

1

No, please don't put using namespace ...; in the global area. You can just do this:

SomeClass.h

// using namespace Example; // never here please

namespace Example
{
    using namespace OtherExample; // this is okay (not global)

    class SomeClass
    {
        ...
        SomeClass someFunction();
        ...
    };

}

SomeClass.cpp

namespace Example // same as in .h
{
    using namespace OtherExample; // this is okay (not global)

    SomeClass SomeClass::SomeFunction()
    {
        ...
    }
}

And I would also suggest with potentially huge namespaces like std:: to never use using namespace std; even within your own namespaces because they simply drag in too many common symbol names.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.