Using the virtual keyword in C++

The great advantage of the C++ language is that it provides tools to write object oriented code that is vastly superior in terms of performance, when compared to other OO languages such as Java and Smalltalk. One of the reasons why C++ generates such fast code is due to its judicious use of the virtual keyword.

A virtual method allows programmers to identify code that is polymorphic, that is, code that can have different implementations based on the actual type of object being used. Polymorphic methods allow for variation of behavior without a need for explicit tests.

For example, lets use a standard Employee hierarchy to present an example of virtual method. Suppose that each Employee class knows how to calculate a salary payment:

class Employee {
 double current_salary;
 double bonus;
public:
virtual double calculatePayment() {
  return current_salary + bonus;
 }
};

The advantage of using such a virtual method is that now we can have different classes that can specialize the default behavior of Employee. For example, we can have a HourlyEmployee with a different implementation:

class HourlyEmployee : public Employee {
 double hourly_salary;
 double hours_worked;
public:
virtual double calculatePayment() {
 return hourly_salary * hours_worked;
 }
};

When not to use the virtual keyword

One of the things that leave C++ learners in doubt is exactly when to use the virtual keyword. On one hand it would be easier to use virtual just everywhere. However there are a few reasons why this would not be the best approach:

There is a small performance penalty for using virtual. If it is not necessary to use virtual methods, then it is better to make that clear to the compiler, so that further optimizations can be performed.

It may be undesirable to use virtual methods when creating a library. If you cannot control who will be using the class, it is better to allow polymorphism only on a case by case situation. For example, we may want to fix the way an Employee is hired for the whole hierarchy of Employees, and in that case it would be wrong to use a virtual method.

Some objects are not polymorphic. For example, a value object generally doesn't need to respond to different situations, since it is concerned only with data storage. In that case, a virtual method is undesirable.

As we see, the virtual keyword is a great way to provide flexibility in C++ objects. However, it is not necessary to use virtual methods everywhere, and in some cases it may be even undesirable. It is better to design a class carefully in order to use virtual methods when they are really needed.

Tags: methods, Virtual, C
Article created on 2012-09-05 11:39:48

Post a comment