Idiomatic Way to declare C++ Immutable Classes

BlamKiwi picture BlamKiwi · Nov 11, 2014 · Viewed 18.7k times · Source

So I have some pretty extensive functional code where the main data type is immutable structs/classes. The way I have been declaring immutability is "practically immutable" by making member variables and any methods const.

struct RockSolid {
   const float x;
   const float y;
   float MakeHarderConcrete() const { return x + y; }
}

Is this actually the way "we should do it" in C++? Or is there a better way?

Answer

chrphb picture chrphb · Nov 11, 2014

The way you proposed is perfectly fine, except if in your code you need to make assignment of RockSolid variables, like this:

RockSolid a(0,1);
RockSolid b(0,1);
a = b;

This would not work as the copy assignment operator would have been deleted by the compiler.

So an alternative is to rewrite your struct as a class with private data members, and only public const functions.

class RockSolid {
  private:
    float x;
    float y;

  public:
    RockSolid(float _x, float _y) : x(_x), y(_y) {
    }
    float MakeHarderConcrete() const { return x + y; }
    float getX() const { return x; }
    float getY() const { return y; }
 }

In this way, your RockSolid objects are (pseudo-)immutables, but you are still able to make assignments.