0

I'm a C++ newbie. Could you tell me why std::vector::front has two definitions, how they are different, and how each of them is called?

The function seems to have two definitions,

  • reference front();
  • const_reference front() const;

I noticed these two definitions, when I looked up the function on the Web. The following two web sites seem to say the same two definitions.

http://www.cplusplus.com/reference/vector/vector/front/

http://en.cppreference.com/w/cpp/container/vector/front

Toshihiro
  • 61
  • 1
  • 1
  • 7

1 Answers1

1

The const version is used by a const this pointer due to overload resolution. It would not be sensible if a non-const object were returned, since then you could hack round the constness.

The non-const version is used by a non-const this pointer. You get back an object that you can modify.

We call this const correctness.