Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the boolean value for a c++ class?

Tags:

c++

class

I want to know how can I set the boolean value for a class. Ive seen this in other peoples code but I cant figure out how to do it myself.The format will be like this:

class myClass{
   //...
};
myClass getClass(){
  myClass myclass;
  //...
  return myclass;
}

int main(int argc, char **argv){
  myClass myclass;
  myclass = getClass();
  if(myclass){
    //do stuff
  }
  //...
  if(!myclass){
    //do other stuff
  }
  return 0;
}
like image 810
sssssss Avatar asked Oct 17 '25 18:10

sssssss


1 Answers

You need to provide a conversion function to bool for your class, like this:

class myClass{
   public:
   explicit operator bool() const { /* ... */ }
};

It's better to make the conversion explicit to avoid accidental conversions. Using it in an if statement is fine, since that is considered an explicit context.

like image 195
cigien Avatar answered Oct 19 '25 07:10

cigien