-1

Can someone explain what is the point of returning by constant reference? I know that when you just return a reference, you are returning an alias to that object you are returning. However, I am not sure what adding the word 'const' changes what it does. Thanks!

Goddrew
  • 125
  • 2
  • 5

2 Answers2

2

A good example would be std::vector::operator[]. There are two overloads of that function, a const version that returns a const reference and a non-const version that returns a regular reference. If you use the const version you cannot assign a new value.

void func(const std::vector<int> & const_vec, std::vector<int> & vec)
{
    const_vec[0] = 906;  // will fail with compiler error
    vec[0] = 906;  // works fine if vec.size() >= 1
}
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

Most times the point in returning a "const ref" (a reference to a constant object) is to give the calling code read only access to the property of a class.

T const & (or const T &) denotes a reference to an object that can't be altered using the reference. Hence only const-qualified member functions can be called.

Swordfish
  • 12,971
  • 3
  • 21
  • 43