Namespaces

Namespaces are like packages in Java, they allow you have the the same function signature multiple times.

Consider the following code:

const double adjust { 0.567 };

namespace Weighted {
    double add(double a, double b) {
        return a + b + adjust;
    }
}

namespace Unweighted {
    double add(double a, double b) {
        return a + b;
    }
}

int main() {
    std::cout << Weighted::add(5.6, 3.2);
    return 0;
}

We have two add functions with the same signature but this OK.because they are in different namespaces. Namespaces can be split between declaration and definition. We call the functions by prefixing the function name with the namespace name and the scope resolution operator.

Namespaces can span different files and en-globe classes also.

If you don’t put your thing in a namespace, it lives in the default global namespace. You can call a function in the global namespace by calling with namespace name or by just prefixing it with the global resolution operator. The compiler will look for the closest match if you call the function bare.

If we don’t want to type the namespace name every time you use a class or function, we can use a namespace declaration. For example the following will bring in the weighted add function and allow us to use it bare.

using Weighted::add;

And the following will bring in the entire weighted namespace, allowing us to use any function or class declared in it bare. Using these pollutes the global namespace so it is a better practice to use the fully qualified name though.

using namespace Weighted;

We can nest namespaces with the inner namespace having direct access to the outer namespaces things. Outer namespaces have to use the fully qualified name of the inner namespace to access its things. The fully qualified name of the inner namespace is outer::inner::function().

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.