If the member function is called through a reference to const
or a pointer to const
, or if it is called directly on an object whose type is const
-qualified, the overload qualified as const
will be picked. Otherwise, the overload not qualified as const
will be picked.
X x;
x.testMethod(); // Calls the non-const version
X const& y = x;
y.testMethod(); // Calls the const version
X* z = &x;
z->testMethod(); // Calls the non-const version
X const w;
w.textMethod(); // Calls the const version
In more formal terms, paragraph 9.3.2/3 of the C++11 Standard specifies (in the quote, cv
stands for const
-or-volatile
, and you can ignore the volatile
part for the purposes of your question):
A cv-qualified member function can be called on an object-expression (5.2.5) only if the object-expression is
as cv-qualified or less-cv-qualified than the member function [...]