C++ Namespace



Source file organization

Rule(s)

Example

// 'Elephant.h' file (declarations):
#ifndef _Elephant // Framing in case of multiple inclusions of this file
#define _Elephant
#include <cstddef> // Predefined entities as 'NULL' or 'nullptr', etc.
… // Other possible inclusions here…
class Elephant {
    static void* _Preallocated_memory;
    …
};
#endif // End of framing

// 'Elephant.cpp' file:
#include <cstddef> // One MUST NOT take into account that 'Elephant.h' already includes '<cstddef>'
… // Other possible standard inclusions here…
#include "Elephant.h" // Access to 'Elephant' class
… // Other possible local inclusions here…
void* Elephant::_Preallocated_memory = nullptr;
Namespace

Example

#include <string>
…
std::string s; // The 'string' type is accessed in an absolute way through its namespace, i.e., 'std'

// Alternatively:
#include <string>
…
using namespace std;
…
string s; // The 'string' type is accessed in a relative way through its namespace

Rule(s)

Example

namespace Franck {
    class C { … };
    …
}

namespace Barbier = Franck;

using namespace Barbier; // Or 'using namespace Franck;'
…
C c; // Instead of 'Barbier::C c;'

Inline namespace

Rule(s)

Example Inline_namespace.Cpp.zip 

namespace New_York_City_Penitentiary {
    inline namespace DAOs {
        class Criminal_case { … };
        …
    }
    …
}
// Later on...
… New_York_City_Penitentiary::Criminal_case … // 'DAOs' namespace is not used!

Example Inline_namespace.Cpp.zip 

namespace New_York_City_Penitentiary {
    …
    namespace Nominal {
        class Prisoner {
        public:
            explicit Prisoner(const std::string&);
            …
        …
    }
    inline namespace Ver_2 {
        class Prisoner {
        public:
            Prisoner(std::string&&);
            …
        …
    }
}
// Later on...
New_York_City_Penitentiary::Nominal::Prisoner::Prisoner(const std::string& prison_file_number) : _prison_file_number(prison_file_number) {}
…
New_York_City_Penitentiary::Prisoner::Prisoner(std::string&& prison_file_number) : _prison_file_number(prison_file_number) {}
…
using namespace New_York_City_Penitentiary;
using namespace std::literals::string_literals; // Operator""s is made visible...

Criminal_case criminal_case; // 'DAOs::Criminal_case' is not required...

Nominal::Prisoner p("1630125388055-29"s); // Explicit "nominal" version...
p.set_date_of_incarceration(std::tm{.tm_mday = 13, .tm_mon = 10, .tm_year = 119}); // 13/11/2019
p.set_incarceration_main(&criminal_case);

Prisoner p_("1630125388055-29"s); // Last version, i.e., 'Ver_2'...
p.set_date_of_incarceration(std::tm{.tm_mday = 13, .tm_mon = 10, .tm_year = 119}); // 13/11/2019
p_.set_incarceration_main(&criminal_case); // Do much: '_offense.insert(criminal_case);'

See also