title: Where to declare/define class scope constants in C++?
body: <p>I'm curious about the benefits/detriments of different constant declaration and definition options in C++.  For the longest time, I've just been declaring them at the top of the header file before the class definition:</p>
  
  <pre><code>//.h
  const int MyConst = 10;
  const string MyStrConst = "String";
  class MyClass {
  ...
  };
  </code></pre>
  
  <p>While this pollutes the global namespace (which I know is a bad thing, but have never found a laundry list of reasons why it is bad), the constants will still be scoped to individual translation units, so files that don't include this header won't have access to these constants.  But you can get name collisions if other classes define a constant of the same name, which is arguably not a bad thing as it may be a good indication of an area that could be refactored.</p>
  
  <p>Recently, I decided that it would be better to declare class specific constants inside of the class definition itself:</p>
  
  <pre><code>//.h
  class MyClass {
      public:
           static const int MyConst = 10;
  ...
      private:
           static const string MyStrConst;
  ...
  };
  //.cpp
  const string MyClass::MyStrConst = "String";
  </code></pre>
  
  <p>The visibility of the constant would be adjusted depending on whether the constant is used only internally to the class or is needed for other objects that use the class.  This is what I'm thinking is the best option right now, mainly because you can keep internal class constants private to the class and any other classes using the public constants would have a more detailed reference to the source of the constant (e.g. MyClass::MyConst).  It also won't pollute the global namespace.  Though it does have the detriment of requiring non-integral initialization in the cpp file.</p>
  
  <p>I've also considered moving the constants into their own header file and wrapping them in a namespace in case some other class needs the constants, but not the whole class definition.</p>
  
  <p>Just looking for opinions and possibly other options I hadn't considered yet.</p>