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.
- You should understand the difference between Static vs. Dynamic Type Pointer and Static vs. Dynamic Dispatching.
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.
- Is the method being called on an object?
- 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.
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!