Lesson 12 | Abstract classes and pure virtual functions |
Objective | Define Pure Virtual Functions and describe their usefulness in creating Abstract Classes. |
Creating Abstract Classes
How pure virtual function is used when creating Abstract Classes
A type hierarchy usually has its base class contain a number of virtual functions. Virtual functions provide for dynamic typing.
These virtual functions in the base class are often dummy functions. They have an empty body in the base class, but they will be given specific meanings in the derived classes. In C++, the pure virtual function is introduced for this purpose. A pure virtual function is a virtual member function whose body is normally undefined. Notationally, a pure virtual function is declared inside the class as follows:
virtual function prototype = 0;
For example:
class Abstract_Base {
public:
//interface - largely virtual
Abstract_Base(); // default constructor
//copy constructor
Abstract_Base(const Abstract_Base&);
// destructor should be virtual
virtual ~Abstract_Base();
// pure virtual function for print
virtual void print() = 0;
...
}
Define Pure Virtual Functions
The pure virtual function is used to defer the implementation decision of the function. In OOP terminology it is called a
deferred method.
A class that has at least one pure virtual function is an
abstract class. It is useful for the base class in a type hierarchy to be an abstract class. It would have the basic common properties of its derived classes, but cannot itself be used to declare objects.Instead, it is used to declare pointers that can access subtype objects derived from the abstract class.
Base Class.
Abstract Classes - Quiz
Click the Quiz link below to take a brief multiple-choice quiz on abstract classes and virtual functions.
Abstract Classes - Quiz