The STL
is full of definitions like this:
iterator begin ();
const_iterator begin () const;
As return value does not participate in overloading resolution, the only difference here is the function being const
. Is this part of the overloading mechanism? What is the compiler's algorithm for resolving a line like:
vector<int>::const_iterator it = myvector.begin();
Overloading on the basis of const type can be useful when a function return reference or pointer. We can make one function const, that returns a const reference or const pointer, other non-const function, that returns non-const reference or pointer.
C++ allows member methods to be overloaded on the basis of const type. Overloading on the basis of const type can be useful when a function returns a reference or pointer.
A const reference is simply that a reference that is const. It does not change the const-ness of the actual object you are passing in. An example of non-const operator overloading: Here is an example of operator overloading where the parameter is not const.
A const function can be called by either a const or non- const object. Only a non- const object can call a non- const function; a const object cannot call it.
The compiler's "algorithm" is like this: Every member function of class X has an implicit argument of type X& (I know, most think it's X*, but the standard states, that for purposes of Overload Resolution we assume it to be a reference). For const functions, the type of the argument is const X&. Thus the algorithm, if a member function is called the two versions, const and non-const, are both viable candidates, and the best match is selected just as in other cases of overload resolution. No magic :)
In the example you gave:
vector<int>::const_iterator it = myvector.begin();
if myvector
isn't const the non-const version of begin()
will be called and you will be relying on an implicit conversion from iterator to const_iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With