3

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;
}
sssssss
  • 53
  • 6

2 Answers2

6

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.

cigien
  • 57,834
  • 11
  • 73
  • 112
0

I see your class design can be improved. Instead of creating a local object, you can just create a pointer of the object, which implicitly takes care and you don't get into the mess of implicit conversion.

For a boolean value [if you really need it], you can directly put a bool as a class member for any additional logic. This expresses the intent directly in the code.

class myClass{
 ...
 bool isOn;

public:
 bool getIsOn(){
     return isOn;
 }
};

Driver :

int main(int argc, char **argv){
  std::unique_ptr<myClass> obj =  std::make_unique<myClass>();
  if(obj){
    //do stuff
  }
  //...
  if(!obj){
    //do other stuff
  }
  return 0;
}
Sitesh
  • 1,816
  • 1
  • 18
  • 25