22

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

Andry
  • 16,172
  • 27
  • 138
  • 246
  • Removed all the meta-tags (the ones that don't really say anything about the question), and the verbose "classification" at the start. Just ask your question, without all the formalities. Makes it much easier for others to read your question. – jalf Apr 11 '11 at 11:02
  • No need to be sorry. :) Just keep in mind that the goal when asking a question is to make it clear, and easy to understand. That means it should contain *only* the information that is necessary, and get to the point right away. We know it's a C++ question because it is tagged as such (and it is in the title), so no need to spend the first 3 lines of the question telling us the same. And we know it is about best practices, because no one ever asks about *worst* practices. Every question here is about **good** ways to do something. ;) – jalf Apr 11 '11 at 11:20

2 Answers2

39

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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • @Andry: No, you cannot. You need to declare them in the header and define them in a separate `.cpp` file. – Jon Apr 11 '11 at 11:11
  • 1
    @Andry: No, you cannot. If you do, you'll get multiple definition error if you include the header file to many cpp file. So the best approach is : the definition should be in .cpp file, as I edited my answer. – Nawaz Apr 11 '11 at 11:14
  • 3
    @Andry: *Can I declare and defined them in header only?* Short answer is no, but there is a longer answer... if the constant is of integral type, you can get away with just *declaring* and assigning the value in the header. The detail is that you can only do this if the integral constant is not *used*, where *used* basically means *used as an lvalue*. I.e. you can use it as a compile time constant or in any circumstance where an rvalue suffices: `int x = 1 + type::constant;`, but not where an lvalue is required: `int const & k = type::constant;`. – David Rodríguez - dribeas Apr 11 '11 at 11:35
  • @Nawaz: For integral constants, it is usually better to provide the value in the declaration, instead of the definition. That enables the compiler to use that value as a compile time constant. `struct test { static const int a = 5; static const int b; }; int const test::a; int const test::b = 7; int array[ test::a ]; /*ok*/ int error[test::b]; /*not ok*/` – David Rodríguez - dribeas Apr 11 '11 at 11:37
  • @David Rodríguez: Nice. I do that usually. I didn't do that now, because there is `const std::string` also, which I can't initialize in the class itself. So for consistency, I did that. :-) – Nawaz Apr 11 '11 at 11:40
5

There is no "best" solution as of course that is a very subjective term.

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

Constants that are not of integer type should be defined as static const members (but you will have to be careful of the order of static initialization if there are any other static objects that refer to these constants).

Constants of integer type can either be declared as static const int or as enums, as you already mention. The discriminating 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,
        };
};

While this is not:

class MyClass {
    public:
        enum {
            Color_Red,
            Vehicle_Car,
        };
};
Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806