r/cpp_questions • • 7d ago

OPEN cpp class vs namespace

in my personal opinion, at least half of the purpose of using nested namespace is to manage visibility, the rust's mod allows it but cpp's namespace does not, only class allows it( the public and private)

is using classes with static functions inside everywhere instead of using namespace an already existing way to use the "namespace" in a way that i can more conveniently manage visibility?

3 Upvotes

12 comments sorted by

View all comments

10

u/kitsnet 7d ago

C++ namespaces are about avoiding name conflicts, not about visibility. One can add a new name or inject another namespace into an already existing namespace, one cannot do that with classes.

Part of the functionality of the namespaces is argument-dependent lookup.

-4

u/Equivalent_Union2768 7d ago

avoiding naming conflicts is the original design intention, but in practice unless for very very large projects there will seldom be the need of avoiding naming conflicts

for the second drawback, i think it matters more, but it is still nice if in future versions of cpp i can have private/public in namespaces

6

u/flyingron 7d ago

It doesn't need to be a large project, it just has to deal with a diverse selection of available libraries.

2

u/kitsnet 7d ago

avoiding naming conflicts is the original design intention, but in practice unless for very very large projects there will seldom be the need of avoiding naming conflicts

"Very very large projects" is what C++ these days is about.

for the second drawback, i think it matters more, but it is still nice if in future versions of cpp i can have private/public in namespaces

As long as you cannot seal namespaces against injection of other functions into them, "private/public" in namespaces has no utility.

1

u/neppo95 7d ago

Why not just use classes/structs? Why do you specifically want to use a namespace for this?

1

u/Equivalent_Union2768 7d ago

this is exactly what i am proposing, using classes +static function everywhere merely for its public/private, having nothing to do with objects

1

u/neppo95 7d ago

Yup, sounds good. Now put all of that code inside a singular namespace in case of a library and you’re golden. If its an executable or otherwise code that won’t get used outside the project, that can be omitted although you’d still run into conflicts possibly for libraries you use.