3 ms·
This reminds me of a conversation I had with a coworker recently about how possible it would be a for an object to check itself for null. Based on this explanat
by prophetjohn 14y ago
This reminds me of a conversation I had with a coworker recently about how possible it would be a for an object to check itself for null. Based on this explanation, it seems like this would definitely be possible in C++ (our conversation was in the context of Java, but it's interesting from an academic perspective)
class NullChecker {
public:
bool isNull() { return !!this; }
};
int main() {
NullChecker *nc = 0;
if(nc->isNull()) doSomething();
return 0;
}
Forgive my C++ syntax as it's been a while, but this seems like it would work to me.
- z92 14y agoTried it. It works. Technically I look at methods as functions with a hidden first parameter that accepts a pointer to the class object's data. If you don't try to dereference that pointer, then the function should work like static member. I was wondering if the compiler will add some check code preventing me from calling any method on a NULL pointed obj. But obviously its permitting it. Of course virtual methods are different. Then you are calling a pointer to a function, the address of which should be stored in your obj data structure.