Why is it common to not include the word ‘class’ in C++ .cpp files?

Let’s view this question from another angle…

It is possible to use the same syntax for both, but it’s “the other one”; the following is perfectly valid:

namespace ns
    int foo();   

int ns::foo() { return 0; }

Looked at like this, it’s the opposite question that’s interesting, “why is it common to include the word ‘namespace’ in .cpp files?”

There’s one substantial difference between namespaces and classes that makes namespace {} necessary in so many places: namespaces are open to extension, but classes are defined entirely by their (one and only) definition.

Like with classes, you can’t add anything to a namespace using the syntax above; you can’t add a function bar above with only int ns::bar() { return 9; }, the only way to add names to a namespace is “from within”.

And, as many have discovered, it’s convenient to wrap an entire file in a namespace and not use the qualified names, even if you’re not adding any names to it.

Hence the popularity of “namespace”: it’s a convenience enabled by the extensibility of namespaces.

Another issue is that the meaning of your “test.cpp” would depend on whether the class definition has already been seen by the compiler – without it, that’s a valid and complete definition of a class with two private functions.
This kind of “action from a distance” depending on possibly very distant code is painful to work with.
It’s also worth noting that namespaces were added some twenty years after “C with classes” was created, when C++ was a well established language, and changing the meaning of a construct that literally hasn’t changed in decades is pretty much unthinkable.
Partularly if all it does is save a few keystrokes.

Browse More Popular Posts

Leave a Comment