C++ TUTORIALS - C++ Namespaces
C++ Namespaces
ADVERTISEMENTS
Defining a Namespace:
namespace namespace_name { // code declarations }ADVERTISEMENTS
name::code; // code could be variable or function.ADVERTISEMENTS
#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; }
Inside first_space Inside second_spaceThe using directive:
#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; } } using namespace first_space; int main () { // This calls function from first name space. func(); return 0; }
Inside first_space
using std::cout;
#include <iostream> using std::cout; int main () { cout << "std::endl is used with std!" << std::endl; return 0; }
std::endl is used with std!Discontiguous Namespaces:
namespace namespace_name { // code declarations }Nested Namespaces:
namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations } }
// to access members of namespace_name2 using namespace namespace_name1::namespace_name2; // to access members of namespace:name1 using namespace namespace_name1;
#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; } } } using namespace first_space::second_space; int main () { // This calls function from first name space. func(); return 0; }
Inside second_space