31

In the boost libraries, there are often examples of including the library like:

#pragma once
#include <boost/property_tree/ptree.hpp>
using boost::property_tree::ptree;

Throughout my program I have been importing namespaces like this:

#include "../MyClass.h"
using namespace MyClassNamespace;

Can someone please explain:

  1. The difference between using and using namespace;
  2. What the advantage of negating the use of using namespace in favour of using;
  3. The differences in forward declaring using and using namespace;

Thanks

Ospho
  • 2,756
  • 5
  • 26
  • 39
  • possible duplicate of [using namespace](http://stackoverflow.com/questions/4906540/using-namespace) – user657267 Jul 28 '14 at 23:54
  • 1
    @user657267 not really. – David G Jul 28 '14 at 23:55
  • @0x499602D2 Well sort of IMO, the linked answer tries to point out that the two statements have completely different use cases, you can't say `using somenamespace` any more than you can say `using namespace notanamespace`. – user657267 Jul 28 '14 at 23:57
  • 1
    @user657267 I saw the linked answer before I published this question, but I didn't think it answered my questions adequately enough – Ospho Jul 29 '14 at 00:09
  • 2
    The correct terms are "using declaration" and "using directive". http://stackoverflow.com/q/16152750/981959 has some relevant answers – Jonathan Wakely Jul 29 '14 at 00:21
  • @redFIVE: This question is now the first result on Google. – davidg Feb 09 '15 at 23:09

2 Answers2

37

using namespace makes visible all the names of the namespace, instead stating using on a specific object of the namespace makes only that object visible.

George Kourtis
  • 2,381
  • 3
  • 18
  • 28
5
#include <iostream>

void print(){
using std::cout; 
using std::endl;
cout<<"test1"<<endl;
}
int main(){
 using namespace std;
cout<<"hello"<<endl;
print();
return 0;
}
  • while using "using namespace std" all the elements under the scope of std are made available under scope of the function.
  • while using "using std::cout" we explicitly mention what element under the std is required for the function ,without importing all the elements under std.

this is my first answer in stack overflow please correct me if iam wrong!!

monish kumar
  • 51
  • 1
  • 1