Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) virtual

 

virtual is a keyword to denote that a class method might have different behaviour in its derived classes.

 

Example

 

Humans say hello differently. In this example there are two kinds of humans that say hello differently: SilentHuman and LoudHuman:

 

#include <iostream>

struct Human
{
  virtual void SayHello() const = 0;
  virtual ~Human() {} // All base classes must have a public virtual destructor [1]
};

struct SilentHuman : public Human
{
  void SayHello() const { std::cout << "...hello...\n"; }
};

struct LoudHuman : public Human
{
  void SayHello() const { std::cout << "HELLO!\n"; }
};

 

Note that it is decided that a plain Human cannot say hello. This can be stated by ending the declaration of SayHello with '=0'. This also makes it impossible to create a Human (you can only create (derived) types of Human). This makes Human an abstract base class.

 

 

 

 

 

References

 

  1. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Item 50: 'Make base class destructors public and virtual, or protected and nonvirtual'

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict