0
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 : https://code.sololearn.com/cPHH3QTLfAS3/?ref=app How this is useful ? Operator as return type...
3 ответов
+ 1
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 ^^ ):
https://code.sololearn.com/c8kU6NQNftmR/?ref=app
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 ):
https://en.cppreference.com/w/cpp/memory/unique_ptr
and alot of the type_trait classes have an implicit bool conversion operator as well:
https://en.cppreference.com/w/cpp/header/type_traits
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.
+ 1
operator is not a return type, its a https://en.cppreference.com/w/cpp/language/cast_operator
0
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 !!!