my theory goes along the lines that the compiler realizes there is no point of using the function with the const return reference. |
No, the compiler can't decide on an overload based on the return type, only based on the parameters passed. As a matter of fact, an overload of a function differing only in the return type is illegal.
The compiler sees that the this parameter is non-const, so it makes a smart guess that the function being called might need to modify it. If that's what you intended and the function being called was const, that would be a problem.
But what is happening when I make the entire class const? |
Don't confuse the terms "class", "object" or "instance", and "pointer to object".
What's happening is that a function that takes a pointer to a variable object (f(T *)) is not the same as a function that takes a pointer to a constant object (f(const T *)). You can pass a 'T *' to either one, but a 'const T *' can only be passed to the latter.
This is what's happening here. const between the closing parentheses and the semicolon or opening brace of a member function means "this function can take a pointer to a constant object as the this parameter". Functions that aren't declared this way can only take pointers to variable objects.
When you cast the pointer to 'const T *', you're guaranteeing that the compiler will only be able to call the overload that can take that as a parameter. If that overload wasn't there, the compiler would complain either about an illegal implicit cast to 'T *', or about not having a matching overload for that parameter type.