Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using namespace & overloaded function

Tags:

c++

namespaces

I don't understand why I get the error "ambiguous call to overloaded function". Before "main", I declared to use namespace "second". My expected output is:

this is the first foo
this is the second foo
this is the second foo

#include <iostream>
using namespace std;

namespace first {
    void foo() {
        cout << "this is the first foo" << endl;
    }
}

namespace second {
    void foo() {
        cout << "this is the second foo" << endl;
    }
}


void foo() {
    cout << "this is just foo" << endl;
}


using namespace second;
void main() {
    first::foo();
    second::foo();
    foo();
}
like image 852
shir k Avatar asked May 30 '26 18:05

shir k


1 Answers

Before "main", I declared to use namespace "second".

When you do this, second::foo is introduced into the global namespace, then for foo(); both second::foo and ::foo are valid candidates.

You can specify that you want to call the global foo explicitly, i.e.

::foo();

Or use using-declaration inside main() instead of using-directive, e.g.

int main() {
    using second::foo;
    first::foo();
    second::foo();
    foo();
}
like image 188
songyuanyao Avatar answered Jun 02 '26 07:06

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!