Search code examples
c++classheader-files

How to create a Class inside of a namespace?


What must the structure of a class look like if it is defined in a separate namespace?

Which parts belong in the header file and which in the cpp file?

How can I make the class accessible only through this specific namespace?


Solution

  • classname.h

    #include <iostream>
    
    namespace N {
        class classname {
        public:
            void classmethod();
        }
    }
    

    classname.cpp

    #include "classname.h"
    
    namespace N {
        void classname::classmethod() {
            std::cout << "classmethod" << std::endl;
        }
    }
    

    main.cpp

    #include "classname.h"
    
    int main() {
        N::classname a;
        classname b; // Error!
    
        a.classmethod();
    
        return 0;
    }