Back Next

Polymorphism

The equivalent code in C++ code uses polymorphism. It is more verbose, but it is less fragile in maintenance mode, and as fast or faster, and uses slightly less storage. The union ID becomes the vptr.
class expression { public:
    virtual ~expression();
    expression();
    virtual char *text() = 0;
    virtual bool is_constant() = 0;
    virtual expr *optimize() = 0;
    virtual void generate_code() = 0;
    etc etc etc }; 
expression_plus::~expression_plus() {
    delete lhs;
    delete rhs; }

expression_plus::expression_plus(expression *a1,
        expression *a2) :
    lhs(a1),
    rhs(a2) { }

bool expression_plus::is_constant() {
    return lhs->is_constant() && rhs->is_constant(); }

void expression_plus::generate_code() {
    lhs->generate_code();
    rhs->generate_code();
    emit_opcode(OP_ADI); } 
class expression_plus:
    public expression { public:
    virtual ~expression_plus();
    expression_plus(expression *, expression *);
    char *text();
    bool is_constant();
    expr *optimize();
    void generate_code();
    etc etc etc private:
    expression *lhs;
    expression *rhs; }; 
Polymorphism
the ability of objects belonging to different types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behaviour. The programmer (and the program) does not have to know the exact type of the object in advance, so this behavior can be implemented at run time. (Wikipedia)