Virtual Method

A virtual method is a method declared within a base class and is re-defined (overridden) by a derived class.

The virtual keyword is used for achieving for dynamic dispatch polymorphic types.

Declare method as virtual or not?

Yes, declare virtual if you expect this method to be overridden by a descendant class:

  • the run-time system will always check to make sure the right implementation is used for any caller

No: do not use virtual if you are sure it won’t be overwritten, since it’s more efficient to let the compiler know in advance the compiler can hardcode method address instead of doing a run-time lookup.

  • Risk: If it is overridden, might get “wrong” definition in some situations.

Which method is called?

From CS247.

REALLY important to remember and understand the difference in dispatching, ask the following questions.

  1. Is the method being called on an object?
  2. Is the method called via a pointer or reference?

Pure Virtual / Abstract Methods

“Pure virtual” methods are abstract in parent, and defined later by children. We declare a pure virtual method by assigning 0 in the declaration.

class Test
{   
public:
    // Pure Virtual Function
    virtual void show() = 0;
   /* Other members */
};

Danger

If you declare a pure virtual function in the base class, you need to make sure that the derived class has an implementation for it!