Search code examples
c++referenceconst-correctnessclass-members

Do class member reference variables have in-built "const-correctness"?


struct A {
  int &r; 
  A (int &i) : r(i) {}
  void foo () const {
    r = 5;  // <--- ok
  }
};

The compiler doesn't generate any error at r = 5;.
Does it mean that &r is already const-correct being a reference (logical equivalent of int* const) ? [Here is one related question.]


Solution

  • I'm not sure exactly what you mean by "already const-correct", but:

    Assigning to r is the same as assigning to whatever thing was passed into the constructor of A. You're not modifying anything in the instance of A when you do this, so the fact that foo is declared const isn't an obstacle. It's very much as if you'd done this:

    struct A {
      int * r;
      A (int * i) : r(i) {}
      void foo () const { *r = 5; }
    }
    

    The fact that foo is const means that it doesn't modify anything in the A instance it's called on. There's no conflict between that and having it modify other data it was supplied with.

    Of course if you happened to arrange for r to be a reference to some member of A then calling foo would modify the instance of A after all. The compiler can't catch all possible ways in which constness of a member function might be violated; when you declare a member function const you're promising that it doesn't engage in any such subterfuge.