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;
}
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.
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