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,
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With