Returning non-const reference from a const member function

int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; }  // obviously bad

In a const-function, every data member becomes const in such way that it cannot be modified. int becomes const int, int * becomes int * const, and so on.

Since the type of a in your first function becomes int * const, as opposed to const int *, so you can change the data (which is modifiable):

  m.geta() = 5;  //works, as the data is modifiable

Difference between : const int* and int * const.

  • const int* means the pointer is non-const, but the data the pointer points to is const.
  • int * const means the pointer is const, but the data the pointer points to is non-const.

Your second function tries to return const int &, since the type of b become const int. But you’ve mentioned the actual return type in your code as int &, so this function would not even compile (see this), irrespective of what you do in main(), because the return type doesn’t match. Here is the fix:

 const int & getb(void) const { return b; }  

Now it compiles fine!.

Leave a Comment