Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function call within same namespace

Tags:

c++

namespaces

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();}
like image 939
Joss Avatar asked Dec 15 '22 09:12

Joss


1 Answers

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.

like image 57
Sergey Kalinichenko Avatar answered Dec 30 '22 14:12

Sergey Kalinichenko