title: How to create immutable structs in C++?
body: <p>Coming from a C# background, I am used to the practice of making <strong>structs immutable</strong>.<br>
  So when I started programming in C++, I tried to do the same with the types that I would usually pass around <strong>by value</strong>.</p>
  
  <p>I had a simple struct which represents a custom index and simply wraps an integer. Because in C++ the <code>const</code> keyword is somewhat similar to <code>readonly</code> in C#, it seemed reasonable to implement my struct like this:</p>
  
  <pre><code>struct MyIndex
  {
      MyIndex(int value) :
          Value(value)
      {
      }
  
      const int Value;
  };
  </code></pre>
  
  <p>The problem with this approach is that this struct behaves quite differently than an immutable struct in C#. Not just that the Value field of a <code>MyIndex</code> variable can not be modified, but also any existing <code>MyIndex</code> variable (local variable or field variable) can't even be replaced with another <code>MyIndex</code>-instance.</p>
  
  <p>So the following code samples do not compile:</p>
  
  <p>a) Using index as a loop variable.</p>
  
  <pre><code>MyIndex index(0);
  
  while(someCondition)
  {
      DoWork();
  
      index = MyIndex(index.Value + 1); // This does not compile!
  }
  </code></pre>
  
  <p>b) Modifying a member field of type <code>MyIndex</code></p>
  
  <pre><code>class MyClass
  {
      MyIndex Index;
  
      void SetMyIndex(MyIndex index)
      {
          Index = index; // This does not compile!
      }
  };
  </code></pre>
  
  <p>These two samples do not compile, the build error is the same:</p>
  
  <blockquote>
    <p>error C2582: 'operator =' function is unavailable in 'MyIndex'</p>
  </blockquote>
  
  <p>What is the reason for this? Why can't the variables be replaced with another instance, despite that they are not <code>const</code>? And what does the build error mean exaclty? What is that <code>operator =</code> function?</p>