1

I am a newbie to C++. So, please bear with me. I was looking into the implementation of the std::vector class. I found the following 2 different implementation of the begin() method. I understand that the first one returns a RW iterator and the second one returns a read-only iterator. I thought that mere difference in return type is not enough for function overloading. How does this work then?

iterator
begin()
{ return iterator(this->_M_impl._M_start); }

const_iterator
begin() const
{ return const_iterator(this->_M_impl._M_start); }
codefx
  • 8,884
  • 14
  • 50
  • 78

2 Answers2

2

One is const and the other isn't. The const version will be called for const std::vector objects while the other is called for non-const std::vector objects. Also note that this also applies to const and non-const references and pointers.

More info on const methods and overloading:

Also relevant:

Community
  • 1
  • 1
Mark Garcia
  • 16,898
  • 3
  • 55
  • 94
0

The implicit "this" parameter is const in the second method. This is enough to distinguish them in overloading.

Emanuele Paolini
  • 9,365
  • 3
  • 35
  • 60