What are namespaces in C++?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for C++ development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Namespaces organize code and prevent name collisions — allowing different libraries or modules to have functions/classes with the same name without conflict. Defining a namespace: namespace Graphics { class Color { ... }; void drawLine(int x1, int y1, int x2, int y2); } namespace Audio { class Sound { ... }; void play(std::string filename); }. Accessing namespace members: Graphics::Color red; Graphics::drawLine(0, 0, 100, 100); Audio::play("music.mp3");. using declaration: bring a specific name into scope: using Graphics::drawLine; drawLine(0, 0, 100, 100); // OK now. using directive (use carefully): bring ALL names from a namespace: using namespace std; // Brings in EVERYTHING from std cout << "Hello"; // OK but pollutes namespace. Never use using namespace std in header files — it pollutes every file that includes the header. OK in .cpp implementation files. Nested namespaces: namespace Company::Project::Module { void function(); } // C++17 inline namespace. Inline namespace (C++11): members are accessible as if in the enclosing namespace — used for versioning: namespace API { inline namespace v2 { void func(); } } API::func(); // Calls v2::func. Anonymous namespace: namespace { int internalHelper() {} // Only visible in this translation unit }. Replaces C's static functions for file-local linkage. std namespace: all standard library components live in the std namespace — std::vector, std::string, std::cout.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last C++ project, I used this when...' immediately makes your answer more credible and memorable.
Previous
What is the difference between stack and heap memory in C++?
Next
What are lambda expressions in C++?