Luca
Luca

Reputation: 322

Class scope constants: const vs static const

For constants of a class, should I use class scope static const, or file scope const?

For example:

// .h
class C {
  private:
    static const int some_constant_c;
}

// .cc
const C::some_constant_c = 10;

vs.

// .h
class C {
}

// .cc
const some_constant_c = 10;

To me, the former one have better semantic meaning that the constant is of a certain class, but the latter one have the advantage not exposing constants to header file.

==============

One follow up question on this:

What if I want my constants be accessed by subclasses. Make sense to put static const in protected? Example follows:

// .h
class C {
  protected:
    static const int some_constant_c;
}

Upvotes: 3

Views: 1448

Answers (2)

Valentin H
Valentin H

Reputation: 7458

I'd prefer 2nd variant, provided the const in the 1st case is private.

Why should one pollute the class declaration with redundant information? Consider, you are implementing a protocol parser, with many many constants. How will the class declaration look like?

Another issue is, why should you type the name of the const twice? I try to keep definition and initialization as close as possible.

Just an opinion.

Upvotes: 2

Sneftel
Sneftel

Reputation: 41542

It's a matter of personal preference, of course. Trying not to expose class internals in the header file is a ship that has most definitely sailed in C++... between member variables and private member functions, it's just not practical to keep implementation details out of the header (unless you're using the pImpl idiom).

If all you want is to hide the value of the constant, note that you can put the initializer in the source file instead.

If you do implement the constants as globals in the source file, use an anonymous namespace to keep them from causing linker collisions.

Upvotes: 4

Related Questions