top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

c++: What is Namespaces? Can someone please explain with an example?

+3 votes
750 views
c++: What is Namespaces? Can someone please explain with an example?
posted Dec 18, 2014 by Amit Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.

Defining a Namespace:

A namespace definition begins with the keyword namespace followed by the namespace name as follows:

namespace namespace_name {
// code declarations
}

To call the namespace-enabled version of either function or variable, prepend the namespace name as follows:

name::code; // code could be variable or function.

Let us see how namespace scope the entities including variable and functions:

#include <iostream>
using namespace std;

// first name space
namespace first_space{
void func(){
cout << "Inside first_space" << endl;
  }
}
// second name space
namespace second_space{
void func(){
cout << "Inside second_space" << endl;
   }
 }
 int main ()
{
  // Calls function from first name space.
  first_space::func();

 // Calls function from second name space.
   second_space::func(); 
   return 0;
   }

If we compile and run above code, this would produce the following result:

Inside first_space
Inside second_space

answer Dec 18, 2014 by Mohammed Hussain
+1 vote

To be precise, namespace defines the scope of the variables/functions that you use in C++.

For example - Your class has a function abc() & suppose there is some library which also has this same function abc().
Now how will the compiler determine that which version of abc() you want to invoke?
Hence namespace comes into picture.

For more info you can follow this link -
http://www.tutorialspoint.com/cplusplus/cpp_namespaces.htm

Hope this helps!

answer Dec 23, 2014 by Ankush Surelia
...