1

For eg., when using OpenCV, we specify using namespace cv; But where does C++ look down to know where it is defined?

Bill Grates
  • 826
  • 1
  • 6
  • 8

2 Answers2

3

using namespace will not make everything declared in that namespace visible. It will expose only what translation unit "sees". Consider following code

One.h

#pragma once
namespace ns
{
  void function1();
}

Two.h

#pramga once
namespace ns
{
  void function2();
}

main.cpp

#include "Two.h" // <-- included only Two.h
using namespace ns;

int main()
{
  function2(); // <-- is a ns::function2() located in Two.h
  function1(); // <-- error compiler does not know where to search for the function
  return 0;
}

What happened here is the compiler created translation unit with all preprocessor directives resolved. It will look something like this:

namespace ns
{
  void function2();
}
using namespace ns;

int main()
{
  function2(); // <-- OK. Declaration is visible
  function1(); // <-- Error. No declaration
  return 0;
}
Teivaz
  • 5,462
  • 4
  • 37
  • 75
  • @BillGates call of overloaded 'function()' is ambiguous. [You can check it yourself](http://coliru.stacked-crooked.com/a/aeda1b74b4749bd2) – Teivaz May 13 '16 at 15:21
  • Ok! Btw the answer was just exactly for what I _intended_ to ask... Thanks – Bill Grates May 13 '16 at 15:23
1

How does C++ know where to look for the namespace specified using using namespace …?

It doesn't.

When you use

using namespace cv;

the scope of search for names (of classes, functions, variables, enums, etc) is expanded. The names are searched in the cv namespace in addition to other scopes in which they are normally searched.

R Sahu
  • 204,454
  • 14
  • 159
  • 270