Understanding how to properly handle C ++ class constants

Consider the following:

namespace MyNamespace{ class MyClass { public: // Public area private: // Private area protected: // Protected area }; /* Class */ } /* Namespace */ 

And think that I would like to define a constant specific to 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 */ 

This way I can get my variable this way (somewhere in my code):

 MyNamespace::MYINT; MyNamespace::MYSTR; 

Is this a good practice? Given that constants can be handled in several ways (for example, numeric constants are often processed using enum ), what is the best approach to defining a constant (related to the class, but which can be useful elsewhere)?

Thankyou

+7
source share
2 answers

If you want the constants to be 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"); 

Use (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:

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

But if the integral constants are not connected, then, in my opinion, it makes no sense to define them as enum .

+14
source

There is no β€œbetter” solution, because, of course, this is a very subjective term.

Given that you mention constants that are used somewhere else, we can say that they must be declared either in protected (if they should be used exclusively by derived classes), or, most likely, in the public section of the class.

Constants that do not have an integer type must be defined as members of the static const (but you need to follow the order of static initialization if there are other static objects that relate to these constants).

Constants of integer type can be declared as static const int or as enumerations, as you already mentioned. The distinguishing factor here is whether two or more constants can be logically grouped together.

For example, this is probably a good idea:

 class MyClass { public: enum { Color_Red, Color_Green, Color_Blue, }; }; 

So far this is not the case:

 class MyClass { public: enum { Color_Red, Vehicle_Car, }; }; 
+1
source

All Articles