Rajesh
Rajesh

Reputation: 1135

Using different namespace in same function

Why I get error message (error: call of overloaded myCout() is ambiguous) when I use two different namespaces in same function making use of using namespace directive without fully qualified name space?

#include <iostream>
using namespace std;

namespace first
{
     void myCout(void)
    {
        cout<<"Hello World is great\n";
    }
}

namespace second
{
     void myCout(void)
    {
        cout<<"Hello Sky is high\n";
    }
}

    int main(void)
    {

        cout<<"Hello World\n";
        using namespace first;
            myCout();

        using namespace second;
            myCout();

        return(0);
    }

If I use fully qualified namespaces for myCout() in second namespace as given below, there is no issue

int main(void)
{
    cout<<"Hello World\n";
    using namespace first;
    myCout();
    second::myCout();
    return(0);
}

Upvotes: 2

Views: 1940

Answers (3)

using directives respect scope. So you can introduce a new block scope to limit the availability of the symbols introduced by each:

int main(void)
{
    cout<<"Hello World\n";
    {
        using namespace first;
        myCout();
    }

    {
        using namespace second;
        myCout();
    }

    return(0);
}

Normally, and so as to avoid conflicts and deep nesting, try to pull in just the identifiers you need with a using declaration instead. If for instance you only ever wanted to use class foo from first then there would be no ambiguity with the following:

using first::foo;
using namespace second;

Upvotes: 6

gsamaras
gsamaras

Reputation: 73366

First you use namespace first, thus the myCout of the first namespace is introduced. Then you use namespace second, causing the other myCout to be come into play too. The second namespace does not override the previous namespace.

As a result, when you call myCout for the second time, there are two definitions into play, causing the compiler to rule this as an ambiguous call.

In other words:

int main(void)
{
    using namespace first;  // `myCout` of the 1st namespace is introduced
    myCout();

    using namespace second; // `myCout` of the 2nd namespace is introduced
    // and does not override the first namespace!

    myCout();               // Which `myCout`? Of the first or second?

    return 0;
}

Upvotes: 1

Mischa
Mischa

Reputation: 2298

using namespace ... directives do not create an ordered path; nor do they override all previous ones. So, yes, your code creates an ambiguous situation.

Upvotes: 3

Related Questions