0

I understand that the keyword const marks variables, parameters etc as read only. In a class declaration why is const used at the end of a member declaration, for example:

QString getClassName() const;
Syzygy187
  • 5
  • 3

2 Answers2

2

Declaring a method const means that the method won't change the state of the object and thus it can be called on const instances of the class.

Notice that const-ness is enforced by the compiler. const methods can't modify member variables unless they are declared mutable. It's very common to have mutable locks so that const methods can still be synchronized.

Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94
1

It basically means that the function is "promising" that it won't change the calling object.

Elenian
  • 144
  • 4
  • 7
  • That's not just a "promise" though, a `const` method can't in fact change the instance state, i.e., the compiler will barf if you try (unless the variable you are trying to modify is marked as `mutable`). – Giovanni Botta Apr 02 '15 at 20:32
  • I understand, I just couldn't think of a better word at that moment. – Elenian Apr 02 '15 at 20:34
  • 1
    And of course you can always cast away the const-ness of the `this` pointer, though mutable is the appropriate way to achieve this. – sfjac Apr 02 '15 at 20:40