34

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

6
  • possible duplicate of using namespace Commented Jul 28, 2014 at 23:54
  • 1
    @user657267 not really. Commented Jul 28, 2014 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. Commented Jul 28, 2014 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 Commented Jul 29, 2014 at 0:09
  • 2
    The correct terms are "using declaration" and "using directive". stackoverflow.com/q/16152750/981959 has some relevant answers Commented Jul 29, 2014 at 0:21

2 Answers 2

42

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.

Sign up to request clarification or add additional context in comments.

Comments

7
#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!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.