When Should You Create A Virtual Function?

June 22nd, 2009 by carlos


One of the questions raised by people starting to use C++ and virtual functions is: when should I use virtual functions?

To answer this question, you need to understand the reason why virtual functions exist in the first place.

A virtual function is a mechanism used for polymorphism in the C++ language. The standard is example is the drawing method of a shape class.

 
class Shape { public virtual void draw(); } 
class Rectangle : public Shape {
  public virtual void draw();
}

What is happening here is that the draw method varies between Shape and Rectangle. Therefore, it doesn’t make sense to have only one implementation. You need to have one version of draw for each of the classes Shape and Rectangle.

Whenever you have a situation where classes in the same hierarchy need different implementations, then virtual is the keyword you need to use. With virtual we are free to redefine a member function on a derived class.

On the other hand, member functions that were not defined with the virtual keyword cannot be redefined by derived classes. The reason for that is that, since “virtual” is not used, the compiler doesn’t know about different versions of the member function on the derived classes. Therefore, the compiler will call the wrong version of the member function.

General Techniques

Programmers diverge on the general technique used to say if a method will be virtual or not. Some people believe that you should make all, or at least most of your methods virtual. The idea is that you never know what might be useful to override later, so it is better to leave the options open.

The other group of developers believe that it is better to define only a few member functions as virtual. The reason is that then you will have more control on what the derived classes can do.

The arguments on both sides are good, and as most things in programming, it comes to choosing a side and sticking to it.

Conclusion

Virtual functions are the main mechanism that allows different behavior for classes in the same hierarchy. In this way, we should be careful in defining what virtual functions are virtual and what are not. Understanding the virtual keyword you have better ways to defining correct behavior in your classes.