C++ overload operator twice, one return non-const reference and the other const reference, what is the preference?
c++, constants, operator-keyword, operator-overloading, reference
Solution
These functions don't overload each other; they have the same signatures, and so the attempt to redefine the same function, which is an error. The return type is not part of a function's signature. To overload a function, you must declare a second function with the same name, but different parameters or `const`/`volatile` qualifiers - that is, qualifiers on the function, not the return type.
(They don't override each other either; overriding is what derived classes do to their base classes' virtual functions).
It's common to define a `const` and a non-`const` overload of a member function; the `const` overload must declare the function `const`, not just the return type:
T& operator()(par_list){blablabla}
const T& operator()(par_list) const {blablabla}
^^^^^
Now the first will be called if you apply `()` to a non-`const` object, and the second on a `const` object. For example:
Thingy nc;
Thingy const c;
nc(); // calls the first (non-const) overload
c(); // calls the second (const) overload
Problem
I overload an operator twice with the same parameter list. but with different return type: ``` T& operator()(par_list){blablabla} const T& operator()(par_list){blablabla} ``` So when I'm calling the () operator, which function would be called based on what preference or situation? I know that if I call () under const function it has to be the const T& one. I'm just curious how C++ deal with such situation and how the default preference works. Thanks