4

What is the correct way to call one function from another from the same namespace when using the 'using namespace' keyword in the implementation? I get following error:

Call to 'bar' is ambiguous

when compiling this:

// Foo.h
namespace Foo
{
    void bar();
    void callBar();
}

// Foo.cpp
#include "Foo.h"
using namespace Foo;

void bar() {/* do something */}
void callBar() {bar();}
2
  • Looks good, must be something else wrong ... Commented Jun 27, 2013 at 10:39
  • 3
    this is exactly why you shouldn't do this! Commented Jun 27, 2013 at 10:44

2 Answers 2

8

It appears that you are providing definitions of bar and callBar in the cpp file. In this case you should put the functions in the namespace Foo where they are declared, rather than importing that namespace with using:

#include "Foo.h"

namespace Foo {

    void bar() {/* do something */}
    void callBar() {bar();}

}

The using namespace directive tells the compiler that you want to call functions and refer to classes from the namespace Foo without qualifying their names explicitly; you can have multiple such directives in your file. It does not tell the compiler that the definitions that you provide below should belong to the namespace Foo, so the compiler dumps them in the top-level namespace.

The end result is that the compiler sees two bars - the Foo::bar() declared in the Foo namespace, with external definition, and ::bar() defined in your cpp file in the default namespace.

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

1 Comment

Aha, that makes perfect sense! Thanks!
5

You have two bars here. one declared in namespace Foo but not defined and another declared and defined in the global namespace. Both are reachable from the call site because you are using using namespace Foo;, hence the ambiguity for the compiler.

If the definitions of the functions are for the ones in the Foo namespace then you should put them in there too.

namespace Foo {
     void bar() {/* do something */}
     void callBar() {bar();}
}

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.