What is the usage of namespaces in C++?

In C++, a namespace is a mechanism used to organize and manage code. It allows a group of related functions, classes, variables, etc. to be encapsulated within a namespace to prevent naming conflicts and code duplication.

You can define your own namespace using the namespace keyword and put related code inside it. For example:

namespace MyNamespace {
    int myFunction(int a, int b) {
        return a + b;
    }
    
    class MyClass {
    public:
        void myMethod() {
            //...
        }
    };
}

In the example mentioned above, MyNamespace is a namespace that contains a function called myFunction and a class called MyClass. When using this code elsewhere, you can access them through the namespace.

int result = MyNamespace::myFunction(3, 4);
MyNamespace::MyClass obj;
obj.myMethod();

Using namespaces in code allows for effective organization and management of code, preventing naming conflicts between different parts. In addition, namespaces can also be nested to create more complex namespace structures.

Another common usage of namespaces is to use namespaces from standard libraries, such as the std namespace.

#include <iostream>

int main() {
    std::cout << "Hello, world!" << std::endl;
    return 0;
}

In the example above, cout and endl are standard library functions and objects under the std namespace. By adding the std:: prefix in the code, we can access these standard library elements in the global namespace.

bannerAds