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();}
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 bar
s - the Foo::bar()
declared in the Foo
namespace, with external definition, and ::bar()
defined in your cpp file in the default namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With