Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Base class

 

A base class is a type of class that is used to inherit member variables and methods from.

Or: a base class is the entity that all derived classes share.

 

The code below shows how an Animal is used as a base class and Cat and Dog are derived classes (of Animal).

 

#include <iostream>

struct Animal //Animal is a (non-abstract) base class
{
  virtual void MakeSound() = 0;
  //All base classes must have a virtual destructor
  // (Herb Sutter & Andrei Alexandrescu, 2004)
  virtual ~Animal() {}
};

//A cat is a-kind-of animal.
//Cat will not be used as a base class,
//therefore it has no virtual destructor
struct Cat : public Animal
{
  void MakeSound() const { std::cout << "Meow" << std::endl; }
};

//A dog is a-kind-of animal.
//Dog will not be used as a base class,
//therefore it has no virtual destructor
struct Dog : public Animal
{
  void MakeSound() const { std::cout << "Bark" << std::endl; }
};

 

A special type of base class is the abstract base class.

 

All base classes must have a (public) virtual destructor. A non-base class must have a (non-public) non-virtual destructor [1].

 

 

 

 

 

References

 

  1. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 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