Check for the absence of this == NULL . Calling a method using the NULL pointer of an object.
If you want to save checks somewhere, you can put it in a smart pointer class, which can take the appropriate action if the held pointer is NULL. If the “appropriate action” is uniquely determined by the type being held, you can use the feature class to indicate it.
Thus, your NULL checks and their logic are stored together and are not mixed with either the caller or the method code.
// specialize this to provide behaviour per held type template <typename T> struct MaybeNullDefaultAction { void null_call() { throw std::runtime_error("call through NULL pointer"); } } template <typename T> class MaybeNull: MaybeNullDefaultAction<T> { T *ptr; public: explicit MaybeNull(T *p) : ptr(p) {} T* operator-> () { if (!ptr) null_call(); // null_call should throw to avoid returning NULL here return ptr; } };
Unfortunately, I see no way to do this without giving up. It is impossible to intercept function calls for all method names, otherwise I would just return *this from operator-> and do the job in operator() .
source share