Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private static const member variable in header vs const variable in cpp

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)?

like image 739
Rufus Avatar asked Oct 05 '17 07:10

Rufus


People also ask

What is the difference between const and static const?

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.

Can static member variables be private?

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.

What is the difference between a static and const variable?

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.

What is the difference between static and const in C++?

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.


1 Answers

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)

like image 162
4 revs, 3 users 89% Avatar answered Oct 22 '22 13:10

4 revs, 3 users 89%