Detecting null dereferences in member functions.

Today’s C++ example involves detecting the use of null pointer dereferences from within your member functions. It’s not common since there’s really not much you can do when you detect this situation, but I find it’s somewhat neat anyways.

The idea is that in a member function, you can examine the value of this, to see if it’s null. If so, you can print out a whine message or something like that.

#include 

using namespace std;

class Test
{
    public:
    void tryToDie() const;
};

void Test::tryToDie() const
{
    if (this == 0) {
        cout tryToDie();

    test = new Test;

    cout tryToDie();

    delete test;

    return 0;
}

If you run that program, you should get output somewhat like the following.

Testing null pointer.
HA!  You tried to dereference a null pointer you silly silly person.
Testing valid pointer.