c++classconstants

Understanding how to correctly treat c++ class constants


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) ?


Solution

  • 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 static member data in the public section of the class:

    //.h file
    class MyClass 
    {
     public:
       //constants declarations
       static const int MYINT;
       static const std::string MYSTR;
    };
    
    //.cpp file
    //constants definitions 
    const int MyClass::MYINT = 12;
    const std::string MyClass::MYSTR = std::string("Hello");
    

    Usage (or access):

    std::cout << MyClass::MYINT << std::endl;
    std::cout << MyClass::MYSTR << std::endl;
    

    Output:

    12
    Hello
    

    Online Demo: http://www.ideone.com/2xJsy


    You can also use enum if you want to define many integral constants and all of them are somehow related, for example this:

    class shirt
    {
     public:
       //constants declarations
       enum shirt_size
       {
            small, 
            medium,
            large,
            extra_large
       };
    };
    

    But if the integral constants are not related, then it wouldn't make much sense to define them as enum, in my opinion.