Pure Virtual Function
“Pure virtual” methods are abstract in parent, and defined later by children. We declare a pure virtual method by assigning 0 in the declaration.
Relation to Abstract Class and Concrete Class:
- A class that declares a pure virtual function is an Abstract Class (cannot be instantiated as objects)
- A class that overrides ALL of its parents pure virtual functions is called a Concrete Class (can be instantiated)
Danger
If you declare a pure virtual function in the base class, you need to make sure that the derived class has an implementation for it.
Pure Virtual Methods can STILL be implemented in the base class
Pure virtual methods don’t have to be implemented, but they still can be. They require an implementation if they will be called.
”= 0 means derived classes must provide an implementation, not that the base class cannot provide an implementation”. See this StackOverflow thread. So what is the point of providing an implementation in the Base Class for a pure virtual function, if the derived classes must ALWAYS provide an implementation anyways? Because there are use cases.
The derived class can explicitly call the base class implementation (if access permissions allow it) by using a fully-scoped name:
The use case I can think of off the top of my head is when there’s a more-or-less reasonable default behavior, but the class designer wants that sort-of-default behavior be invoked only explicit
Uses cases:
- When you want derived classes to always perform their own work but also be able to call a common set of functionality.