Should my classes be in a namespace?
-
Is it recommended to declare your classes inside a namespace or some type of scoping mechanism? I'm used to java where the practice is to declare classes inside packages which are essentially a scoping mechanism. Globals can be placed into packages also. But it seems odd that if I want to put a class definition into a namespace I need to wrap the class declaration into
namespace mynamespace { // my class declaration here }
is this the proper practice in Qt or is there a one line way to indicate all items in a file are for a particular namespace? Is namespace how scope is best designated in Qt or is there a different means to do this? In java scope is basically indicated by a one line package declaration.
package com.s3.peripheralconnection; // my class declaration here
-
Namespaces are not Qt specific. It's a C++ thing. Qt by default doesn't use them for classes, but puts globals, enums etc. in Qt namespace. You can also configure Qt to put everything in a namespace if you experience name clashing.
As for whether or not you should use namespaces in your own code - that's up to you. They are not required. Some projects use them, some don't. It's polite to put your code in a namespace if you're making a library that gets included somewhere, so that you don't pollute somebody's code.
@James-Mark-Chan said:
is there a one line way to indicate all items in a file are for a particular namespace?
No, namespaces in C++ are enclosed in braces. File is not a particularly interesting data unit in C++, apart from some minor scoping details. A more common scope is a translation unit which can be composed of several files.