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
No this is not possible. The compiler can't know which version you want, it deducts it from the parameters. You can overload many times, but not by the return type.
Overloading on the basis of const type can be useful when a function returns a reference or pointer. We can make one function const, that returns a const reference or const pointer, and another non-const function, that returns a non-const reference or pointer.
Once you have a const object, it cannot be assigned to a non-const reference or use functions that are known to be capable of changing the state of the object.
Overloading with same arguments and different return type −No, you cannot overload a method based on different return type but same argument type and number in java. same name. different parameters (different type or, different number or both).
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
You can't overload a function/method based on return type. I would expect the compiler to throw an error here. What you can do is specify the method itself as a const
method, using
const T& operator()(par_list) const {blahblah}
The const
qualifier not only means this can be called on a const
receiver, but it also is used in the overload resolution. This happens because it affects the implicit *this
parameter that's passed to the method; a const
method uses a const
qualifier on *this
, and const
qualifiers are taken into account during overload resolution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With