Whats the difference between

using namespace NameSpaceName;

and

namespace NameSpaceName;

?

Recommended Answers

All 4 Replies

The first one is 'using' the second one is 'creating'.

But I can be using namespace std for example, and still making my own functions, classes etc.. If I am just "using" it then does it mean, my function names are still in global namespace, and are not in std's namespace?

If you wrapper your functions inside the std namespace, they belong to the std namespace.
Namespaces are used to help avoid collisions, so (in essence) the same named function/class/etc. can exist in multiple namespaces without interfering with others.

>>If I am just "using" it then does it mean, my function names are still in global namespace

Yes. The using statement simply makes it so that you don't have to qualify the namespace anymore when you _use_ things from that namespace. It doesn't mean that your code gets added to that namespace. Here's a quick example:

#include <iostream>

namespace foo {

  void print1() { 
    std::cout << "printing in foo!" << std::endl;
  };

};

namespace bar {
  
  using namespace foo;

  void print2() {
    std::cout << "printing from bar!" << std::endl;
  };

  void print3() {
    print1();     //call foo::print1() without needing foo::
  };
  
};

int main() {
  foo::print1();  //OK
  bar::print2();  //OK
  bar::print3();  //OK
  foo::print2();  //ERROR: print2 is not a member of namespace 'foo'
  print1();       //ERROR: print1 is not a member of the global scope.
  bar::print1();  //ERROR: print1 in not a member of namespace 'bar'
};

You get the idea, adding things to namespace 'bar' even though it uses namespace 'foo' will not add those things to the 'foo' namespace. And the logic goes the other direction too (e.g. "print1" from 'foo' does not get added to namespace 'bar'). So the using namespace statement is simply to shorten the syntax, but you can get into trouble, as so:

//.. as before

namespace bar {
  
  using namespace foo;

  void print1() {
    std::cout << "printing from bar!" << std::endl;
  };

  void print2() {
    print1();     //ERROR: print1() is ambiguous, do you mean bar::print1 or foo::print1.
  };
  
};

Sometimes, problems like that don't get caught by the compiler (because of overloading and argument-dependent look-up). And you get silent errors.

commented: I admire your ability to exhaust an answers! +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.