Virtual Function Mechanics
If you really wanted to avoid virtual functions, you could emulate dynamic binding by providing your own type resolution code. Suppose you are maintaining a class hierarchy of zoo animals [Lip91], where ZooAnimal is your base class:
class ZooAnimal { public: ... virtual void draw(); int resolveType() {return myType;} private: int myType; ... }
The rest of the animals in the zoo are derived from ZooAnimal. The resolveType() method will enable you to distinguish a Bear from a Monkey at run-time.
class Bear : public ZooAnimal { public: Bear (const char *name) : myName(name), myType(BEAR) {} void draw(); ... };
Each animal sets its appropriate type in its constructor.
If you wanted to draw all animals in the zoo, you ...
Get Efficient C++ Performance Programming Techniques now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.