It is desirable to have constants (e.g. certain strings or numbers) to be defined at some central point. In order to keep readability of the code well, it is also desirable have easy access to those constants. During my research for good practices to achieve this I have now found the following two solutions (https://stackoverflow.com/a/9649425/2776093).
FoodConstants.h:
namespace FoodConstants {
namespace Fruits {
extern const string Apple;
...
}
...
}
FoodConstants.cpp:
namespace FoodConstants {
namespace Fruits {
const string Apple = "apple" ;
...
}
...
}
FoodConstants2.h:
class FoodConstants {
public:
class Fruits {
public:
static const string Apple;
...
}
...
}
FoodConstants2.cpp:
const string FoodConstants::Fruits::Apple = "apple"
...
For both solutions I can access the the apple constant with FoodConstants::Fruits::Apple anywhere in the program where the .h is included. Initialization is done in the same compilation unit and initialization problems are avoided. I have noticed one difference: For the second solution I can't, e.g., do a "using namespace FoodConstants" to abbreviate the access to the string constant with Fruits::Apple.
Are there any other differences? Is there a preferred way to organize constants like this?