C++ Namespaces

  1. What is Namespace

    Namespaces are a way of preventing name conflicts in projects
  2. How to write namespace

    To create namespace you use namespace keyword and in {} you can define functions/variables/etc
    namespace test {
        void print(const char* message){
            std::cout << message << std::endl;
        }
    }
    You access namespace by using name and :: and then name of function/variables/etc
    namespace test {
        void print(const char* message){
            std::cout << message << std::endl;
        }
    }
     
    test::print("hello world");
    If you don't want to write namespace name and :: you can use directive using namespace and then namespace name. It will allow you to use defined functions/variables/etc without writing that :: stuff.
    namespace test {
        void print(const char* message){
            std::cout << message << std::endl;
        }
    }
     
    using namespace test;
    print("hello world")
    or you can specify what namespace and function/variable/etc you are using using using and then function/variable/etc name after.
    namespace test{
        void print(const char* message){
            std::cout << message << std::endl;
        }
        void log(const char* message){
            std::cout << "LOG: " << message << std::endl;
        }
    }
     
    using test::print; 
    print("lalala") // you can use this without test::
    log("lalala") // you cant use this without test::