For example:
operator bool() const { return col != 0; }
col
is an int. How does operator bool() const
work?
bool operator() is a function operator, making the instantiated object a functor. But operator bool() is an implicit conversion operator converting the object to bool . Note that #include <bits/stdc++.
Conversion Operators in C++ C++ supports object oriented design. So we can create classes of some real world objects as concrete types. Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator.
Member functions of the form
operator TypeName()
are conversion operators. They allow objects of the class type to be used as if they were of type TypeName
and when they are, they are converted to TypeName
using the conversion function.
In this particular case, operator bool()
allows an object of the class type to be used as if it were a bool
. For example, if you have an object of the class type named obj
, you can use it as
if (obj)
This will call the operator bool()
, return the result, and use the result as the condition of the if
.
It should be noted that operator bool()
is A Very Bad Idea and you should really never use it. For a detailed explanation as to why it is bad and for the solution to the problem, see "The Safe Bool Idiom."
(C++0x, the forthcoming revision of the C++ Standard, adds support for explicit conversion operators. These will allow you to write a safe explicit operator bool()
that works correctly without having to jump through the hoops of implementing the Safe Bool Idiom.)
operator bool() const { return col != 0; }
Defines how the class is convertable to a boolean value, the const
after the ()
is used to indicate this method does not mutate (change the members of this class).
You would usually use such operators as follows:
airplaysdk sdkInstance; if (sdkInstance) { std::cout << "Instance is active" << std::endl; } else { std::cout << "Instance is in-active error!" << std::endl; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With