Idiomatic Way to declare C++ Immutable Classes

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.

Leave a Comment