I have seen the following code:
template <class T>
class Type {
public:
Type() {}
T& operator=(const T& rhs) {value() = rhs; return value();}
T& value() {return m_value;}
T value() const {return m_value;}
private:
T m_value;
};
Why does the compiler not complain about
T& value() {return m_value;}
T value() const {return m_value;}
and how to know which one is invoked?
But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible. Java can distinguish the methods with different method signatures.
Method Signature According to Oracle, the method signature is comprised of the name and parameter types. Therefore, all the other elements of the method's declaration, such as modifiers, return type, parameter names, exception list, and body are not part of the signature.
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).
Two Methods cannot have same method signature. Methods can have same method name, and this process called method overloading.
The two functions are actually not the same. Only the second function is declared as a const
member function. If the object that the member is called from is const
, the latter option is used. If the object is non-const
, the first option is used.
Example:
void any_func(const Type *t)
{
something = t->value(); //second `const` version used
}
void any_func2(Type *t)
{
something = t->value(); //first non-`const` version used
}
If both functions were declared non-const
or both were declared const
, the compiler would (should, anyway) complain.
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