Namespace Program Example using CPP

    1. Home
    2. Tutorials
    3. CPP
    4. CPP Programs
    5. Namespace
    6. Program

    Source Code:

    #include <iostream>

    // standard namespace
    using namespace std;

    // defining first namespace
    namespace first {
        void display() { // identical function
            cout<<"Function from first namespace"<<endl;
        }
    }

    // defining second namespace
    namespace second {
        void display() {
            cout<<"Function from second namespace"<<endl;
        }
    } // end of namespace

    int main(int argc, char** argv) {
        { using namespace first;
        display();
        } // end of first namespace scope
        
        // start of second namespace scope
        { using namespace second;
        display();
        } 
        
        return 0;
    }

    Output:

    cpp namespace example program using Dev-C++

    Working:

    This program example elaburate use and importance of namespace in CPP. The most commonly used standard namespace is also used here using namespace directive. After this we define two user defined namespaces as first and second. These both namespaces have display() function.

    In main function we use opening and closing delimeters to define the scope of namespace. When we want to use multiple namespaces in main function then it is necessary to encapsulate each namespace along with namespace directive into curly parenthesis.

    This program is compiled and tested using Dev-C++.

    Comments
    Login to TRACK of Comments.