1
#include <iostream>
#include <cstdlib>

namespace A {
    int a = 10;
    void get_value(){ std::cout << "a = " << a << std::endl; }
}

namespace B {
    int b;
    void get_value(){ std::cout << "b =" << b << std::endl; }
}

void set_B();

int main(){

    using namespace A; 
    get_value(); 
    set_B();

    system("PAUSE");
    return 0;
}

void  set_B(){
    using namespace B;
    b = 15;
    get_value();    // Why call to get_value() is ambiguous, error is not generated here ?
 }

Why call to get_value() inside set_B() function is not ambiguous ( A::get_value() or B::get_value()) as both appear as ::get_value() inside set_B().

quantdev
  • 23,517
  • 5
  • 55
  • 88
curious_kid
  • 379
  • 1
  • 4
  • 8
  • 1
    Why do you think they both appear as `::get_value()`? – juanchopanza Aug 15 '14 at 12:55
  • @juanchopanza as using namespace B; statement inside set_B() introduces B::get_value() into global namespace and statement using namespace A; inside main() introduces A::get_value() into global namespace. – curious_kid Aug 15 '14 at 13:00
  • Please read: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Matt Aug 15 '14 at 13:03
  • @matt thanks for the link . I know using namespace std; is not a good practice. That's why I have used std::cout in the above code. I am beginner in C++ that's why I'm playing with the code. :) – curious_kid Aug 15 '14 at 13:11
  • OK where you go wring is "introduces ... *into global namespace*". The `using` only have effect in their enclosing scope. – juanchopanza Aug 15 '14 at 13:24
  • 1
    @juanchopanza So It means that using namespace A; inside main() has no effect inside the set_B() function. So get_value() inside set_B() only refer to B::set_value(). Hence no error. – curious_kid Aug 15 '14 at 13:29

2 Answers2

3

using namespace A; isn't active inside set_B because it only appears inside main. It is limited to the scope in which it appears: the body of main.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • But moving it to global namespace scope is causing call to get_value() is ambiguous compile time error . – curious_kid Aug 15 '14 at 13:06
  • @curious_kid Ah, that's right, `using namespace` does not import the namespace into the scope it appears. But its effect is limited to that scope. Updated. – Potatoswatter Aug 15 '14 at 22:57
0

because A::get_value and B::get_value arn't normally visible in the global scope. the using namespace statement makes the declarations in that namespace visible inside set_B.

programmerjake
  • 1,794
  • 11
  • 15