Search code examples
c++classscopenamespacesobjectname

object name identical to namespace name: redeclaration


Why is it an issue when an object defined in the file scope has the same name as an existing namespace? Why is this ok in the function scope (e.g. inside main)?

Example:

#include <iostream>

namespace foo {
    class Foo {};
}

namespace bar {
    class Bar {};
}

// foo::Foo foo; // <-- This will give error

int main () {
    bar::Bar bar;  // <-- This is ok

    std::cout << "Program ran successfully" << std::endl;
    return 0;
}

The error I get is

ns_main.cpp:11:10: error: ‘foo::Foo foo’ redeclared as different kind of symbol
 foo::Foo foo;
          ^
ns_main.cpp:3:15: error: previous declaration of ‘namespace foo { }’
 namespace foo {

This situation is quite easy to achieve if a lot of files are included where a lot of different namespaces have been defined.

Can someone explain this? Thanks! Cheers


Solution

  • The same identifier can be declared and used in different, possibly nested scopes, but not in the same one. Your problem has nothing to do with the fact that the namespaces are defined at file scope. Moving them into another namespace outer does not solve the error:

    #include <iostream>
    
    namespace outer {
      namespace foo {
        class Foo {};
      }
    
      namespace bar {
        class Bar {};
      }
      foo::Foo foo; // <-- This will still give an error
    }
    
    int main() {
      outer::bar::Bar bar; // <-- This is still ok
    }
    

    The variable bar in bar::Bar bar; however belongs to another, more local scope than the namespace bar. The variable foo in foo::Foo foo; and the namespace foo are in the exact same scope.

    As most of your variables and namespaces should not not be declared in global/file scope, having many namespaces is not a problem at all.