A namespace in CPP is used to define a scope in order to differentiate similar functions, classes, variables etc. to define the context in which names are defined for the same name available in different libraries.
Syntax: Defining Namespace
namespace namespace_name
{
// code declarations
}
Syntax: Calling the defined name
namespace_name :: code; // code could be variable or function.
Example:
#include <iostream> using namespace std; namespace str1 { void display() { cout<<"I am the First String!"<<endl; } } namespace str2 { void display() { cout<<"I am the Second String!"<<endl; } } int main() { str1::display(); str2::display(); return 0; } |
Output
I am the First String! I am the Second String! |