0

In the book "Programming Interviews Exposed" by John Mongan (see page 33), theres a function declaration for a Singly Linked List Element:

const T& value() const {...}

I understand what everything before the method name means, namely that it is a reference to a template datatype which you may not modify, but what does the extra const after the value() signify? A constant reference? I thought references were already constant (i.e. unchangeable alias which is the object).

P4L
  • 98
  • 3
  • 9
  • References are not always constant, i.e. `const int&` is not the same as `int&`. In the first case, you can refer (alias) and `int` but cannot modify it, and can also bound the `const int&` to a temporary, whereas in the last case you refer (alias) an `int` and are able to change it. In the latter case, you CANNOT bind a temporary to a non-const reference, as C++ standard forbids you, unless you are using Microsoft's compiler, which has a way of cheating everything. – vsoftco Nov 27 '14 at 01:20

2 Answers2

3
const T& value() const {...}

This means the function value() will return a const T& type and in between (in the function) won't modify the class itself. Say I write:

class Cfoo
{
    void foo() const
    {
        //Cfoo will not be modified here
    }
}

If I directly quote from MS Docs:

Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. A constant member function cannot modify any non-static data members or call any member functions that aren't constant.

MHN
  • 103
  • 2
  • 7
deeiip
  • 3,319
  • 2
  • 22
  • 33
  • So essentially this is saying that both the caller and callee cannot change the class members – P4L Nov 27 '14 at 01:12
  • The caller can't modify a private member anyway, but even a constant member function can't do that. – deeiip Nov 27 '14 at 01:21
0

The const after the method name signifies that the method does not modify any field of the object. Therefore, it can be invoked on a const instance of the object.

Arthur Laks
  • 524
  • 4
  • 8