is it valid if I define member functions with same name¶meters but different return types inside a class like this:
class Test {
public:
int a;
double b;
}
class Foo {
private:
Test t;
public:
inline Test &getTest() {
return t;
}
inline const Test &getTest() const {
return t;
}
}
Which member function gets called if we have following code?
Foo foo; // suppose foo has been initialized
Test& t1 = foo.getTest();
const Test& t2 = foo.getTest();
No. Neither a method class nor a non-class function.
The reason is ambiguity. There would be situation in which the compiler could not pick the right overloading only by deducing the returned value.
In conclusion: you can't overload methods based on return type.
In your example, those two methods:
Are correctly overloaded because the signature is different, but not because the return value is different!
Indeed, a function signature is made up of:
So the signature of your methods are:
As you can notice, the return value is not part of signature, but the const of the method qualifier is.
With the following code:
It will call only the no-const method, even in the case
t2
.The reason is that
foo
object isno-const
in that scope, so each method will be called in its no-const form.In details, in the third line:
foo.getTest()
will return theno-const
reference and after will be implicitly converted in aconst
reference.If you want to force the compiler to call the
const
version, you should "temporary convert" the objectfoo
in aconst
.For example:
In that case I get a
const
ref to the object, so the object will be treated like aconst
and the proper const method will be invoked.no, it is not valid, but in your example it is, because the last
const
is actually part of the signature (the hiddenFoo *this
first parameter is nowconst Foo *this
).It is used to access in read-only (get const reference, the method is constant), or write (get non-const reference, the method is not constant)
it's still a good design choice to return the reference of the same entity (constant or non-constant) in both methods of course!
Const and non-const methods with the same formal parameter list can appear side-by-side because the this pointer is treated as a hidden argument and would have a different type. This may be used to provide mutating and non-mutating accessors as in the code in your question.
If the signatures are exactly the same, then no.
To expand upon the previous answers and your given code with an example so you can actually tell what's being called when:
With output:
The
const
you see after the second getTest signature tells the compiler that no member variables will be modified as a result of calling this function.No.
You cannot overload on return type.
Why? The standard says so.
And it actually makes sense - you can't determine what function to call in all situations.