Pure Virtual / Abstract

We can now define classes with inheritance, call super constructors, and super destructors. By now we know almost everything needed to implement all our class designs. The only thing left is "abstract" methods.

pure virtual function

C++ speak for "abstract method". Function, since this is what C++ calls methods in objects. Virtual, because it is to be overridden. And "pure" since it has to be overriden.

To denote pure virtual functions make then virtual and add a = 0 (equals zero) between the argument list and the semicolon. Example:

  virtual void someFunction(int param, float moreParam) = 0;

This is one of the rare cases where you actually have to use = 0 and NOT an expression that evaluates to 0 (e.g. = 1-1). However, whitespace doesn't matter, so =0 would also work.

Abstract class. Remember from the OO Section:

Abstract class

Abstract classes contain (or inherit) at least one abstract method. Abstract classes can not be instantiated.

In C++ there is no explicit notion for abstract classes. (But don't forget it when you model!)

So here's a complete example of an abstract class:

class FinancialManager {
  virtual bool shouldIInvestIn(string what) =0;

And an example of overriding:

class BigSpender : public FinancialManager {
  virtual bool shouldIInvestIn(string what) { return true; }


Give the definition (not the implementation) of these 3 classes:

class StreetVehicleV2 {
  virtual float gCS() = 0;

class Motorcycle: public StreetVehicleV2 {
  virtual float gCS();

// somewhere else:
float Motorcycle::gCS() {
// ...