Nice article, but I just wanted to throw out that if being able to call a class method on a null object in C++ is desirable, you can actually check for that condition instead of just crashing.
if(!this) return false; // Or whatever
Of course it's open for debate as to whether this is something to encourage, but it can help from having to use a Null Object pattern in some situations.
No, you really can't do this. If you think you can, tell me what you think the output of this program will be:
class X
{
int a;
public:
X() : a(123) { }
int get_a() { return this ? a : 1; }
};
class Y
{
int b;
public:
Y() : b(456) { }
int get_b() { return this ? b : 2; }
};
class Z : public X, public Y
{
int c;
public:
Z() : c(789) { }
int get_c() { return this ? c : 3; }
};
#include <iostream>
int main()
{
Z *z = NULL;
std::cout << z->get_a() << '\n';
std::cout << z->get_b() << '\n';
std::cout << z->get_c() << '\n';
}
That's a good point, calling a virtual method on a null pointer is the source of some backtraces that seem to start a few bytes past 0.
Naming things is always difficult, but I meant class method, although what I should have said was non-virtual class method, which is possible in C++. Both virtual and non-virtual have "this" pointers, the difference is whether the class method to call is looked up at runtime or compile-time, so I still would consider both "methods". I didn't learn OOP from Smalltalk so I may be abusing the terminology (it's not intentional).
I believe the correct terminology for C++ would be "member function", and specifically "non-virtual member function" for the ones that actually work with NULL. I also wouldn't be surprised if using a non-virtual member function with NULL is actually undefined behavior that just happens to work with popular compilers, although I'm too lazy to look up the standard to see.
"Class method" is usually used to refer to methods that class objects have themselves, as opposed to an "instance method", which is a method that instances of a class possess. C++ doesn't have class objects or class methods.