Game Development Reference
In-Depth Information
class Sub2 : public Sub1
{
public:
// If you create a new subclass inheriting from Sub2 and attempt
// to override this method, the compiler will kick out an error.
virtual void Go(void) sealed;
};
C# and other languages have been doing this for a long time now. I ' m happy to see
C++ starting to do the same.
Let the Compiler Help You
If you ever change the nature of anything that is currently in wide use, virtual
functions included, I suggest you actually change its name. The compiler will
find each and every use of the code, and you
'
ll be forced to look at how the
original was put to use. It
s up to you if you want to keep the new name.
I suggest you do, even if it means changing every source file.
'
When you decide to make a function virtual, what you are communicating to other
programmers is that you intend for your class to be inherited from by other classes.
The virtual functions serve as an interface for what other programmers can change.
By overriding your virtual functions and choosing whether or not to call your imple-
mentations, they are changing the behavior of your class. Sometimes this is exactly
what you intend. The Process class you
'
ll see in Chapter 7,
Controlling the Main
Loop,
has a virtual VOnUpdate() method that is meant to be overridden to allow
you to define the behavior of your specific process.
Oftentimes, making an Update() function virtual is not the best way of doing
things. For example, say you have a class that processes a creature. You have an
update function that runs some AI, moves the creature, and then processes colli-
sions. Instead of making your update function virtual, you could make three sepa-
rate protected virtual functions: one for AI, one for movement, and one for
collision processing, each with a default implementation. The subclass can over-
ride one or more of these functions, but not the update function. So subclasses
can
t change the order of operations, they can only change what happens at each
step.Thisiscalledthetemplate method design pattern and is very handy. In fact, I
used it recently at work to allow subclasses to redefine how interactions are cho-
sen and scored.
If you ' re on the other side and trying to extend a class by deriving a subclass from it
and overriding some virtual functions, you should make sure that you
'
re doing it for
the right reasons. If you find yourself significantly altering its behavior, you should
'
 
Search WWH ::




Custom Search