C++ Null Pointer Magic
C++ allows you to do magic, it is completely safe to call a method on a nullptr
.
#include <iostream>
class Magic
{
public:
void tada(void)
{
std::cout << "Magic! (" << this << ")" << std::endl;
}
};
int main(int argc, char *argv[])
{
Magic *m = nullptr;
m->tada();
return 0;
}
The above successfully prints:
Magic! (00000000)
Why? because we're never actually accessing the address of the object. If we added a field to the class. Let's say int a
and we try to access it in tada()
. Then the program will crash due to an Access violation reading location 0x00000000
.