Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach to define a constant (used in a constant expression) in the class?

Tags:

c++

constants

I am trying to define a constant BUFFER_LENGTH for my class for a given usecase.

//1. Using preprocessor declaration
//#define BUFFER_LENGTH  12

//2.Global constant
//const int BUFFER_LENGTH  = 12;
class MyRequest
{
public:
    //3. Define an in-class constant
    //static const int BUFFER_LENGTH = 12;

    //4. Declare an enum constant
    enum 
    {
        BUFFER_LENGTH = 12
    };

    MyRequest()
    {
        strcpy(mBuffer, "TestString");
        printf("Buffer: %s, BUFFER_LENGTH = %d",mBuffer, BUFFER_LENGTH);
    }
private:
    char mBuffer[BUFFER_LENGTH];
};

I just listed down the different ways in which constant can be defined for the class.

1. Using Preprocessor constant
2. Using Global constant
3. Using in-class constant
4. using an enum.

Out of these, which is the best approach to define the constants for the given use case? I prefer to use the enum constant over others approaches. Is there any other better approach which I have missed out.

Thanks,

like image 349
aJ. Avatar asked Apr 06 '09 11:04

aJ.


2 Answers

An enumerate type is not meant to define a numeric constant, though it's (ab)used for that a lot in template-metaprogramming.

If the constant's meaning is entangled with the class, I would define it in there. Then you're still having two choices:

 class WithConst {
 public:

     // 1. as a const static member variable
     static const int sc_nNumber = 100; // I can initialize here for
                                        // integral-types only

     // 2. as a static member function - possibly inlined.
     static int sf_nNumber() { return 100; }
 };

The plus-side of the second choice is that you don't need to alter any client code later when you want to e.g. read the constant out of the registry, or a config file.

like image 96
xtofl Avatar answered Oct 05 '22 04:10

xtofl


It is always better for maintenance purposes to restrict the scope of any name (be it function, variable or constant) as much as possible. So I would suggest either

static const int BUFFER_LENGTH = 12;

or

enum { BUFFER_LENGTH = 12 };

inside the class definition.

There isn't much benefit to the former, except that you can explicitly control the type. enum causes C++ to choose an unspecified integral "underlying type" for you -- it could be as small as char if your enum contains only small values, though empirically, most compilers by default will use an int.

like image 30
j_random_hacker Avatar answered Oct 05 '22 05:10

j_random_hacker