Why should I declare a private static const
variable in header (and initialize it in cpp) instead of just defining + declaring it in the cpp?
i.e.
case1.h
class MyClass
{
...
private:
static const MyType some_constant;
}
case1.cpp
const MyType MyClass::some_constant = ...;
case2.h
//No mention of some_constant at all
case2.cpp
const MyType some_constant = ...;
Assuming common c++ conventions are followed (1 header & cpp is only associated with 1 class, never #include
.cpp file), in both cases, the variable is private to the class, both are initialized before the constructor is called, both provide the function of being a "static class local constant".
Is there any difference between the above two approaches? (And which one is preferable)?
The const variable is basically used for declaring a constant value that cannot be modified. A static keyword is been used to declare a variable or a method as static. A const keyword is been used to assign a constant or a fixed value to a variable.
Static member variables It is essentially a global variable, but its name is contained inside a class scope, so it goes with the class instead of being known everywhere in the program. Such a member variable can be made private to a class, meaning that only member functions can access it.
The short answer: A const is a promise that you will not try to modify the value once set. A static variable means that the object's lifetime is the entire execution of the program and it's value is initialized only once before the program startup.
The main difference between Static and Constant function in C++ is that the Static function allows calling functions using the class, without using the object, while the Constant function does not allow modifying objects.
Since it's a private
member, only the implementation of the class can access it.
Therefore, in the interests of not unnecessarily polluting your class definition, I'd be inclined to adopt the second approach.
You could go one step further and define it in an anonymous namespace:
namespace {
const MyType some_constant = ...;
}
in that way, it is certainly localised to a single translation unit. Note however that your using const
implies internal linkage by default. (Without const
, the variable would be accessible by others using extern
)
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