Naveen kumar
Naveen kumar

Reputation: 183

does operator overloading in C++ really expect a return value?

I don't understand the difference between the following snippets. One has a return value and the other doesn't. What really is the difference? When to use what? Looking forward to receiving your answers.

bool Distance::operator < (Distance d2) const 
{
    float bf1 = feet + inches/12;
    float bf2 = d2.feet + d2.inches/12;
    return (bf1 < bf2) ? true : false;
}
operator float() const        //conversion operator
{                          //converts Distance to meters
    float fracfeet = inches/12; //convert the inches
    fracfeet += static_cast<float>(feet); //add the feet
    return fracfeet/MTF; //convert to meters
}

Upvotes: 3

Views: 233

Answers (2)

Build Succeeded
Build Succeeded

Reputation: 1150

Actually, whenever we overload the operator its developer responsibility to keep operator behavior the same as mentioned in language. As we develop the piece of code that can be used by thousands of users, each doesn't have time to check the implementation of our code.

The principle of least astonishment means that a component of a system should behave in a way that most users will expect it to behave; the behavior should not astonish or surprise users.

https://www.modernescpp.com/index.php/c-core-guidelines-rules-for-overloading-and-overload-operators

Upvotes: 1

arrowd
arrowd

Reputation: 34401

The last one is a conversion operator, so it is implied that it returns a float - you convert your value to this type.

As for operator<, it has return type because you can actually make it whatever you like. For instance, operator<< for C++ standard library streams do I/O instead of logical shifting.

Upvotes: 8

Related Questions