I have the following code in my application. Why do we use the const
keyword with the return type and after the method name?
const T& data()
The const
(and volatile
) qualifier binds to the left. This means that any time you see const
, it is being applied to the token to the left of it. There is one exception, however; if there's nothing to the left of the const
, it binds to the right, instead. It's important to remember these rules.
In your example, the first const
has nothing to the left of it, so it's binding to the right, which is T
. This means that the return type is a reference to a const T
.
The second const does have something to the left of it; the function data()
. This means that the const
will bind to the function, making it a const
function.
In the end, we have a const function returning a reference to a const T.