C++ - Namespaces

Overview

Estimated time: 25–35 minutes

Avoid name collisions and group APIs with namespaces. Learn using declarations vs using directives and their trade-offs.

Learning Objectives

  • Declare and use namespaces.
  • Understand using declaration vs using directive.

Prerequisites

Basics

namespace math { int add(int a,int b){ return a+b; } }
int main(){ int x = math::add(2,3); }

using declarations vs directives

using math::add;   // bring a single name
using namespace std; // bring many names (avoid at global scope)

Common Pitfalls

  • using namespace std; at global scope in headers—pollutes users' namespaces.

Checks for Understanding

  1. When is a using directive acceptable?
Show answers
  1. In a local scope or source file when carefully contained.

Exercises

  1. Create two functions with the same name in different namespaces and call each with qualified names.