7

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

Rufus
  • 5,111
  • 4
  • 28
  • 45

1 Answers1

5

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)

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
Bathsheba
  • 231,907
  • 34
  • 361
  • 483