Robben_Ford_Fan_boy
Robben_Ford_Fan_boy

Reputation: 8738

Where to store Class Specific named constants in C++

If you have a class that has some named constants, what is the best practive for storing the constants:

Option 1: Namespace in Class header

So in my class header I will have:

class myClass
{
...
...
};

namespace NamedConstants
{
   const string Bucket = "Bucket";
}

Option 2 Member Constants

class MyClass {      // this goes in the class
private:                          // header file
  static const string Bucket;
  ...
};

... and in the class implementation file:

const string MyClass::Bucket = "Bucket";

I actually prefer Option 1, considering it to be cleaner: the variable name and value appear together. Also, if you give the namespace a good name then it can make code more readable when you use constants:

TrafficLight::Green

Does anybody see any issue with this method over Option 2?

Upvotes: 3

Views: 3356

Answers (2)

sbi
sbi

Reputation: 224179

If the strings are meant to be seen/used by users of the class, you wouldn't consider to make them private class members. So I conclude they are not meant to be seen/used by users of the class. But then it doesn't make sense to put them into the header at all.

If you put them into the class (or into namespace scope into the header), then all changes to their type and identifier will force clients to recompile their code.

If you put them into the class' implementation file, they are a private detail of the class' implementation and changes to them only force recompilation of the class' implementation.
If you put them into an unnamed namespace, they cannot collide with any other name:

namespace  {
  namespace NamedConstants
  {
     const string Bucket = "Bucket";
  }
}

Upvotes: 3

Peter G.
Peter G.

Reputation: 15144

Option 1 could lead to a separate string object for every file which includes the header. So it depends among others on how scarce your resources are.

Upvotes: 1

Related Questions