Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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
}
like image 213
Naveen kumar Vunnam Avatar asked Dec 07 '25 05:12

Naveen kumar Vunnam


1 Answers

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.

like image 136
arrowd Avatar answered Dec 08 '25 18:12

arrowd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!