27

Is the following C++ code valid?

namespace Foo
{
    class Bar
    {
        // Class code here.
    };
}

namespace Foo
{
    namespace Bar
    {
        void SomeFunction();
        {
            // Function code here.
        }
    }
 }

In other words, can there be a namespace with the same name as a class?

jww
  • 97,681
  • 90
  • 411
  • 885
Maxpm
  • 24,113
  • 33
  • 111
  • 170
  • Possible duplicate of [Using a class in a namespace with the same name?](http://stackoverflow.com/questions/1539333/using-a-class-in-a-namespace-with-the-same-name) – jww May 05 '17 at 18:11

3 Answers3

19

"can there be a namespace with the same name as a class?"

No, If they are in the same namespace, as in your case.

Otherwise, yes. Anything can have the same name as anything else if they are in different namespaces. See this stackoverflow thread as reference.

Ozair Kafray
  • 13,351
  • 8
  • 59
  • 84
19

You cannot have the arrangement you have in your question because there is no way to disambiguate Bar.

My compiler says:

error C2757: 'Bar' : a symbol with this name already exists and therefore this name cannot be used as a namespace name
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 1
    The compiler can't just check to see if I'm calling something in the `Bar` namespace or the `Bar` class? – Maxpm May 02 '11 at 12:09
  • 6
    @Maxpm: The compiler has to disambiguate `Bar` first before it checks inside. If you call `Foo::Bar::SomeFunction();`, then should the compiler say 'OK' or should it say 'Error' - class Bar has no member? – quamrana May 02 '11 at 12:13
3

No, but you can have SomeFunction be a static member of the Bar class.

namespace Foo
{
    class Bar
    {
        // Class code here.
        static void SomeFunction()
        {
            // Function code here.
        }
    };
}

The result is not 100% equivalent to what you want (because of ADL) but the qualified names are what you expect.

alfC
  • 14,261
  • 4
  • 67
  • 118