O'Reilly logo

Efficient C++ Performance Programming Techniques by David Mayhew, Dov Bulka

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required