Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of "operator bool() const"

For example:

operator bool() const  {      return col != 0;  } 

col is an int. How does operator bool() const work?

like image 301
Cheng Avatar asked Jan 05 '11 02:01

Cheng


People also ask

What is bool operator() in c++?

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++.

What is C++ conversion operator?

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.


2 Answers

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.)

like image 199
James McNellis Avatar answered Sep 18 '22 08:09

James McNellis


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; } 
like image 44
langerra.com Avatar answered Sep 21 '22 08:09

langerra.com