Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

C++ Namespaces Scope Resolution Nesting: Tutorial, Examples, FAQs & Interview Tips

What is a Namespace?

A namespace is a declarative region that provides a scope for identifiers (names of types, functions, variables). Namespaces prevent name collisions - two libraries can both define a function called print() without conflict if they're in different namespaces.

The entire C++ standard library lives in the std namespace - that's why you write std::cout or use using namespace std;.

Defining and Using Namespaces
#include <iostream>
using namespace std;

namespace Math {
    const double PI = 3.14159265358979;

    double circleArea(double r) { return PI * r * r; }
    double square(double x)     { return x * x; }
}

namespace Graphics {
    void draw() { cout << "Drawing shape..." << endl; }
    double square(double x) { return x * x; }  // same name, different namespace
}

int main() {
    // Access with scope resolution operator ::
    cout << Math::PI << endl;
    cout << Math::circleArea(5) << endl;
    cout << Math::square(4) << endl;    // 16
    cout << Graphics::square(4) << endl; // 16 - no conflict!

    Graphics::draw();

    // using declaration - bring one name into scope
    using Math::PI;
    cout << PI << endl;  // no Math:: needed

    // using directive - bring entire namespace into scope
    using namespace Math;
    cout << circleArea(3) << endl;

    return 0;
}

Nested Namespaces and Aliases

Nested Namespaces and Anonymous Namespaces
#include <iostream>
using namespace std;

// Nested namespace
namespace App {
    namespace Utils {
        void log(const string &msg) {
            cout << "[LOG] " << msg << endl;
        }
    }
    namespace DB {
        void connect() { cout << "DB connected" << endl; }
    }
}

// C++17 nested namespace shorthand
namespace App::Config {
    const string VERSION = "1.0.0";
}

// Namespace alias - shorter name for long namespace
namespace AU = App::Utils;

// Anonymous namespace - internal linkage (like static in C)
namespace {
    int internalCounter = 0;  // only visible in this file
    void increment() { internalCounter++; }
}

int main() {
    App::Utils::log("Starting app");
    App::DB::connect();
    cout << App::Config::VERSION << endl;

    AU::log("Using alias");  // shorter

    increment();
    increment();
    cout << "Counter: " << internalCounter << endl;  // 2

    return 0;
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.