Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does overloading of const and non-const functions work?

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();
like image 972
davka Avatar asked Feb 24 '11 10:02

davka


People also ask

Can const functions be overloaded?

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.

Can we overload const functions in C++?

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.

What is const in operator overloading?

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.

Can a const function call a non-const function?

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.


2 Answers

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 :)

like image 82
Armen Tsirunyan Avatar answered Sep 23 '22 19:09

Armen Tsirunyan


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.

like image 41
Flexo Avatar answered Sep 21 '22 19:09

Flexo