title: C++ defining a constant member variable inside class constructor
body: <p>Usually when you have a constant private member variable in your class, which only has a getter but no setter, it would look something like this:</p>
  
  <pre><code>// Example.h
  class Example {
      public:
          Example(const int value);
          const int getValue() const;
      private:
          const int m_value;
  };
  
  
  // Example.cpp
  #include "Example.h"
  
  Example::Example(const int value)
  : m_value(value)
  {
  }
  
  const int Example::getValue() const
  {
      return m_value;
  }
  </code></pre>
  
  <p>Now what I'm trying to do, is have a constant int member variable like that, but instead of defining it in the initializing section like so: <code>: m_value(value)</code> I need to take an other object - I'll use a vector in this example - as the constructor's parameter, and set m_value based on the parameter object. In this case, I'll try to do vector's size + 1, if the size is above 0. So this is what I did:</p>
  
  <pre><code>Example::Example(std::vector&lt;Example*&gt; myVec)
  {
      if (myVec.size()) {
          m_value = myVec.size() + 1;
      }
      else {
          m_value = -1;
      }
  }
  </code></pre>
  
  <p>But I get an error <code>uninitialized member 'Example::m_value' with 'const' type 'const int'</code> and if I init m_value inside the initializing section, I get the error <code>assignment of read-only data-member 'Example::m_value'</code> which all makes sense to me, I'm supposed to get those errors, but how could I go around them?</p>
  
  <p><strong>Edit:</strong> Only way I could edit <code>m_value</code> is inside the object itself (since m_value is private). Having only getter would limit me from setting m_value to anything other than what it's set in the constructor. Do I benefit anything from having constant int as a member variable? </p>