Pure virtual functions are functions that do not need to be defined in the base class but must be overwritten in the derived class. The novelty "= 0" syntax can be used to declare a virtual function as a pure virtual function. For example:
Class base {
Public:
Void F1 (); // not a virtual function
Virtual void F2 (); // virtual function, but not pure virtual function
Virtual void F3 () = 0; // pure virtual function
};
Base B; // error: pure virtual F3 not overridden
Here, base is an abstract class (because it has a pure virtual function), so it cannot be used to define objects directly: Base (obviously) is used for base classes. For example:
Class derived: public base {
// F1 is not defined: It doesn't matter.
// F2 is not defined. It doesn't matter. It inherits base: F2.
Void F3 ();
};
Derived D; // OK: derived: F3 overwrites base: F3
Abstract classes are a good tool for defining interfaces. In fact, a class with only pure virtual functions is usually called an interface.
Of course, you can also define pure virtual functions:
Base: F3 (){}
This is often of little significance (although it provides some simple public code for the derived class), and the base: F3 () needs to be overwritten in the derived class ().
If you do not overwrite a pure virtual function in a derived class, the derived class is also an abstract class:
Class D2: public base {
// F1 is not defined: It doesn't matter.
// F2 is not defined. It doesn't matter. It inherits base: F2.
// F3 is not defined: It doesn't matter, but D2 is also an abstract class.
};
D2 D; // error: the pure virtual function base: F3 is not overwritten.