Considering the following piece of code.
#include <iostream>
using namespace std;
class Object
{
public:
Object() {}
void Print() const
{
cout << "const" << endl;
}
void Print()
{
cout << "mutable" << endl;
}
};
void print_obj(const Object& obj)
{
obj.Print();
}
int main()
{
Object obj1;
const Object obj2;
Object*const pobj1 = &obj1;
print_obj(obj1);
print_obj(obj2);
obj1.Print();
obj2.Print();
pobj1->Print();
return 0;
}
The output is
const
const
mutable
const
mutable
I am wondering, how does C++ decide which method to invoke, when facing many mutable methods with the same name?
The function to be called is evaluated on the basis of the cv-qualifier(
const/volatile) of the passed object. Note that cv-qualifiers are considered while function overload resolution.If passed object is
const, function receivingconstargument is selected.If passed object is non-const then function receiving non-const argument is selected.If the object is
constthen only callconstmember function can be called.If the object is non-const then the non-const version is prefferred over the
constversion.The rules are clearly specified by the standard.
Reference:
C++03 standard:
§13.3.1 Candidate functions and argument lists:
So if the object is
constcompiler will pick version of member function which has implicit object parameter of type reference to constObjectwhich is const version ofPrint().