Return type as operator | importance | SoloLearn: Learn to code for FREE!


Return type as operator | importance

Hi Something new i came across... As we know constructor or destructor don't have return type where as all other functions have some or other data type as return type. Below is sample code : How this is useful ? Operator as return type...

6/26/2020 7:15:57 PM

Ketan Lalcheta

3 Answers

New Answer


It doesn't make much sense to do it here, but there are certainly situations where an implicit ( or an explicit ) conversion would be useful. For example I made a class that would allow comparisons like if( 5 < x < 10 ) { ... } to compile which used an implicit bool conversion operator to avoid an ugly function call. Another place where I used it is in ( not trying to advertise or anything ^^ ): Where it allows me to simply check if a pointer manager object contains a valid pointer by simply doing if( ptr ){} as if it was a normal pointer. You'll see that the C++ library also has one ( under Observers ): and alot of the type_trait classes have an implicit bool conversion operator as well: Another example where I used an implicit conversion operator is for a BigInt library where I used operator std::string() const To allow the big integer to be implicitly convertible to a string. That is about it for my examples, I don't use it that often unless it makes sense to have it. Certainly not something you should now throw into every class you make. Just don't do it if the objects are unrelated, like in your example, it probably won't make sense to do this then. The implicit operator conversion doesn't convert the entire class like an reinterpret_cast btw, they are completely different.


operator is not a return type, its a


Okay... I was also surprised with the way it has been used.... What to do by assigning unrelated object... Isn't this a bad design or am I missing something ? Also I was not in favour of reinterpret_cast and now this I came across... What's the need to convert non related objects !!!