Hey everyone, I'd just like to share a little trick I found with C++ that helped make the use of classes much nicer. [and partially for more experienced programmers to say that it's a terrible idea, heheh]
The 'trick' is simply that class functions can be called from a null pointer.
For example, say you have a class for a quake-style console. It has a simple interface of console::newtext(char *). Generally you'd like to use it to bump out error messages, game information, things like that. But how do you know if it's been setup already? You could make a singleton of it, but what about more complex things that might require multiple instances? You could assume a lot of things about game state, but what if something blows up the console, or if you can't make those assumptions?
You could check that the global *gConsole exists each time you want to send info to it:
if (gConsole){
gConsole->newtext("Monkeys.");
}
But that just gets a little repetative, and what if you or other users forget to check?
Using the little trick, you can do something like this:
void console::newtext(char *intext){
//
//
//
if (!this){
return;
}
// otherwise proceed as normal
}
Now gConsole::newtext will always "succeed", even if the actual display hasn't been setup yet, or if something unexpected has destroyed it. All of those if (gConsole) checks get moved into a reusable piece of code.