0

I've been looking over some code in C++ and came across an object being the boolean conditional for an if statement. This is confusing to me as it does not seem to fulfill the true/false criteria needed for if statements. I could understand if the statement was checking for null but the follow code does not make sense to me.

if(!mObject)
{
    mObject = new Object();
}

Can someone explain why you can do this?

BTW, the code works when it is run.

tzg
  • 616
  • 1
  • 8
  • 17
  • Two possibilities: 1) The variable is a pointer, and then `!mObject` is true if `mObject` is a null pointer. 2) If `mObject` is an instance of a class or structure, it has overloaded the `!` operator. – Some programmer dude Jul 23 '19 at 17:26
  • 2
    @Someprogrammerdude Or `operator bool()` (possibly `explicit`) – Justin Jul 23 '19 at 17:27
  • Falsy things in C++: `false`, `0`, `0.0`, `0.0f`, `-0.0`, `-0.0f`, `'\0'`, `nullptr` and other things that evaluate to zero. (Note: `NaN` is not falsy in C++.) – Eljay Jul 23 '19 at 18:51

0 Answers0