Consider the following:
namespace MyNamespace{
class MyClass {
public:
// Public area
private:
// Private area
protected:
// Protected area
}; /* Class */
} /* Namespace */
And consider that I would like to define a constant which is specific for my class.
I usually do the following:
namespace MyNamespace{
// Constants
const int MYINT = 12;
const std::string MYSTR = std::string("Hello");
// Class definition
class MyClass {
public:
// Public area
private:
// Private area
protected:
// Protected area
}; /* Class */
} /* Namespace */
In this way I can get my variable in this way (somewhere in my code):
MyNamespace::MYINT;
MyNamespace::MYSTR;
Is this a good practice?
Considering that constants can be treated in several ways (for example numeric constants are often treated using enum), what is the best approach to define a constant (related to a class, but that can be also useful somewhere else)?
Thankyou
If you want the constants specific to the class and also want them to be useful somewhere else as you said, possibly outside the class, then define them as
staticmember data in thepublicsection of the class:Usage (or access):
Output:
Online Demo: http://www.ideone.com/2xJsy
You can also use
enumif you want to define many integral constants and all of them are somehow related, for example this:But if the integral constants are not related, then it wouldn’t make much sense to define them as
enum, in my opinion.