Why and How to Use Namespaces in C++

Why doesn't ANSI C have namespaces?

C does have namespaces. One for structure tags, and one for other types. Consider the following definition:

struct foo
{
int a;
};

typedef struct bar
{
int a;
} foo;

The first one has tag foo, and the later is made into type foo with a typedef. Still no name-clashing happens. This is because structure tags and types (built-in types and typedef'ed types) live in separate namespaces.

What C doesn't allow is to create new namespace by will. C was standardized before this was deemed important in a language, and adding namespaces would also threaten backwards-compatibility, because it requires name mangling to work right. I think this can be attributed due to technicalities, not philosophy.

EDIT:
JeremyP fortunately corrected me and mentioned the namespaces I missed. There are namespaces for labels and for struct/union members as well.

Why and how should I use namespaces in C++?

Here is a good reason (apart from the obvious stated by you).

Since namespace can be discontiguous and spread across translation units, they can also be used to separate interface from implementation details.

Definitions of names in a namespace can be provided either in the same namespace or in any of the enclosing namespaces (with fully qualified names).

How do you properly use namespaces in C++?

Namespaces are packages essentially. They can be used like this:

namespace MyNamespace
{
class MyClass
{
};
}

Then in code:

MyNamespace::MyClass* pClass = new MyNamespace::MyClass();

Or, if you want to always use a specific namespace, you can do this:

using namespace MyNamespace;

MyClass* pClass = new MyClass();

Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).

And as you asked below, you can use as many namespaces as you like.

Namespaces in C

When using namespace prefixes, I normally add macros for the shortened names which can be activated via #define NAMESPACE_SHORT_NAMES before inclusion of the header. A header foobar.h might look like this:

// inclusion guard
#ifndef FOOBAR_H_
#define FOOBAR_H_

// long names
void foobar_some_func(int);
void foobar_other_func();

// short names
#ifdef FOOBAR_SHORT_NAMES
#define some_func(...) foobar_some_func(__VA_ARGS__)
#define other_func(...) foobar_other_func(__VA_ARGS__)
#endif

#endif

If I want to use short names in an including file, I'll do

#define FOOBAR_SHORT_NAMES
#include "foobar.h"

I find this a cleaner and more useful solution than using namespace macros as described by Vinko Vrsalovic (in the comments).

Why are namespaces used?

For small, self-contained projects, there's not much need for namespaces, and you'd never create a namespace for each object or concept in your code.

Larger projects using libraries benefit from being isolated from names introduced by those libraries, as well as some internal organisation to make readability easier.

Similarly, when creating a library, it's a good idea to put its contents into a namespace so as not to cause headaches and conflicts for your users (as you don't know how large their projects will be, and what names they may want to use themselves).

To use an analogy: if you have three books, you don't bother organising them alphabetically. But, once you have a hundred, you might decide to categorise them on your bookshelf for easier reference and mental health.

And, if you now borrow another twenty books from a friend, you'd probably keep those in a separate pile so they're easier to find when you need to give them back.

So, to some degree, this is a case of… you'll know why you need it, when you need it.

What is namespace used for, in C++?

Namespace is used to prevent name conflicts.

For example:

namespace foo {
class bar {
//define it
};
}

namespace baz {
class bar {
// define it
};
}

You now have two classes name bar, that are completely different and separate thanks to the namespacing.

The "using namespace" you show is so that you don't have to specify the namespace to use classes within that namespace. ie std::string becomes string.

What exactly is a namespace and why is it necessary

From cppreference.com:

Namespaces provide a method for preventing name conflicts in large
projects.

Symbols declared inside a namespace block are placed in a named scope
that prevents them from being mistaken for identically-named symbols
in other scopes.

Multiple namespace blocks with the same name are allowed. All
declarations within those blocks are declared in the named scope.

A namespace works to avoid names conflicts, for example the standard library defines sort() but that is a really good name for a sorting function, thanks to namespaces you can define your own sort() because it won't be in the same namespace as the standard one.

The using directive tells the compiler to use that namespace in the current scope so you can do

int f(){
std::cout << "out!" << std::endl;
}

or:

int f(){
using namespace std;
cout << "out!" << endl;
}

it's handy when you're using a lot of things from another namespace.

source: Namespaces - cppreference.com

Appropriate use of namespace in C++

When you see :: in C++, it doesn't mean namespace. :: is the scope resolution operator. There are different ways to define scope in C++, Namespaces and Classes are two of these ways. Explaining their differences, pros, and cons is outside the scope if your original question.

To answer what you're asking in a more roundabout way, yes, putting functions inside Classes and Namespaces is Good C++. Otherwise, your functions will all wind up in the Global scope. Which makes for very messy programming and defeats much of the design of C++.

However, simply writing Foo::Baz() does not define Foo as a class or namespace either.

To properly use a namespace, one would first declare it and then declare the member functions as such:

namespace MyCoolNamespace {
void aFunction();
void anotherFunction(bool b);
}

And then define the functions like so:

void MyCoolNamespace::aFunction()
{
/* something this function does */
}

It can then be called the way the tutorial mentions (however keep in mind, the tutorial's scope is a class, not a namespace!)

MyCoolNamespace::aFunction();

or called with the assistance of the using the using keyword:

using namespace MyCoolNamespace;

aFunction();


Related Topics



Leave a reply



Submit