CodeBlanks Logo Icon CodeBlanks

Defining namespaces

Learn to define a namespace with the namespace keyword.

Namespaces with namespace

In large projects, functions or variables with the same name can clash. C++ solves this with namespace; you group related declarations under a name.

namespace math {
    int add(int a, int b) {
        return a + b;
    }
}

Here the add function lives inside the math namespace. To call it from outside, you write math::add(2, 3). The :: is the scope resolution operator and lets you reach the items inside a namespace.

The scope resolution operator

To access an item inside a namespace from outside, you use the :: operator. The namespace name comes first, the item name second.

int n = math::add(2, 3);  // n = 5

Here math::add calls the add function inside the math namespace. The same operator is also used to reach class members and global variables. With nested namespaces you chain them: outer::inner::foo().

Practice math namespace and call

Define namespace math. Inside it write the function int add(int a, int b) { return a + b; }. In main, call it with int n = math::add(2, 3);, print with cout << n << endl;.

Starter code

main.cpp
#include <iostream>
using namespace std;

// Define the math namespace

int main() {
    // call the function in the namespace and print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
using namespace std;

namespace math {
    int add(int a, int b) {
        return a + b;
    }
}

int main() {
    int n = math::add(2, 3);
    cout << n << endl;
    return 0;
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which keyword is used to define a namespace?

  • package
  • module
  • namespace Correct answer
  • scope

Explanation: In C++ a namespace is defined with namespace.

2 Fill in the blank: namespace call

Question
int n = math____:add(2, 3);
Answer
int n = math::add(2, 3);

Explanation: The :: operator reaches the item in a namespace.

3 Match each expression with its purpose

Term Meaning
namespace math defines a namespace
math::add calls the inner function
:: scope operator

All lessons in Beginner