T& f() { // some code ... }
const T& f() const { // some code ... }
I\'ve seen this a couple of times now (in the introductory book I\'ve b
But why would you have both functions in one and the same class definition?
Sometimes you want to provide different semantics for same operation depending on whether it's being invoked on const
object OR non-const
object. Let's take an example of std::string
class:-
char& operator[](int index);
const char& operator[](int index) const;
In this case when operator[]
invoked through const
object you won't let user to change the content of the string.
const std::string str("Hello");
str[1] = 'A'; // You don't want this for const.
On the other hand,In case of non-const string you let user to change the content of string. That's why a different overload.
And how does the compiler distinguish between these?
Compiler checks whether that method is invoked on const
object OR non-const
object and then appropriately call that method.
const std::string str("Hello");
cout << str[1]; // Invokes `const` version.
std::string str("Hello");
cout << str[1]; // Invokes non-const version.