Namespace in C++


The namespace mechanism is used for the logical grouping of program elements like variables, class, functions, etc. If some program elements are related to each other they can be put into a single namespace. The purpose of the namespace is to localize a name of identifiers to get rid of naming conflicts across different modules designed by different members of the programming team. The namespace defines the scope of the identifiers.

Code Example:

using namespace std;

namespace one {
    void sum(int a, int b) {
        int c = a*a + b*b;
        cout<<"inside namespace one "<<c<<endl;

namespace two {
    void sum(int m, int n) {
        cout<<"inside namespace two "<<m + n;

int main() {
    int num1, num2;
    one::sum(num1, num2);
    two::sum(num1, num2);
    return 0;


In the above code, two namespaces are created, (one, two). But both the namespace have the same function (sum). To call our desire function, we have to specify the namespace also.

Calling syntax will be, namespace_name::element_inside_namespace(variables, functions).


inside namespace one 1908
inside namespace two 54

Source: The Secrete of Object Oriented Programming in C++

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments