Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ identical method signature but different return type

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?

like image 210
agentsmith Avatar asked Oct 21 '15 16:10

agentsmith


People also ask

What happens when the method signature is the same and the return type is different?

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.

Can return types affect 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.

Can a function with same name have different return types?

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).

Can two methods have the same signature?

Two Methods cannot have same method signature. Methods can have same method name, and this process called method overloading.


1 Answers

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.

like image 173
owacoder Avatar answered Nov 08 '22 15:11

owacoder