November 1999
Intermediate to advanced
336 pages
6h 29m
English
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 ...
Read now
Unlock full access