CodeBlanks Logo Icon CodeBlanks

Summary - Namespaces

Combine namespace, using and alias to write a helper module.

Summary: Helper module

In this summary we will combine namespace, using and alias to build a small helper module. The helper namespace contains a few useful functions; we import them with using and shorten long names with an alias.

The plan: first define the helper namespace with square and cube functions. Then import them with using namespace helper; and add the alias namespace h = helper;. This brings the namespace tools together in a single task.

Practice Build the helper module

Define namespace helper { int square(int x) { return x * x; } }. Add the alias namespace h = helper;. In main, call int n = h::square(5);, print with cout << n << endl;.

Starter code

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

// Define the helper namespace
// Define the h alias

int main() {
    // call square with the alias and print
    return 0;
}

Sample solution

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

namespace helper {
    int square(int x) { return x * x; }
}
namespace h = helper;

int main() {
    int n = h::square(5);
    cout << n << endl;
    return 0;
}

Expected output

25

Questions and answers

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

1 Match each tool with its job

Term Meaning
namespace helper namespace definition
using namespace helper import
namespace h = helper short name

2 What does namespace h = helper; provide?

  • A new namespace
  • A nested namespace
  • A using directive
  • A short name for helper Correct answer

Explanation: The h alias is a short name for helper.

3 Fill in the blank: using directive

Question
using namespace ____;
int n = square(5);
Answer
using namespace helper;
int n = square(5);

Explanation: using namespace helper makes square callable directly.

All lessons in Beginner