Abstract classes can be created by defining pure virtual methods and how you can
use abstract classes as a polymorphic interface for derived classes. To
illustrate this we will be implementing an inhomogeneous list, that is, a linked
list whose elements can be of various class types.
Pure Virtual Methods
The base class Coworker
// Coworker.h: Defining the abstract class Coworker. // ---------------------------------------------------- #ifndef _COWORKER_H #define _COWORKER_H #include <string> #include <iostream> using namespace std; class Coworker { private: string name; // more information public: Coworker( const string& s = ""){ name = s; } virtual ~Coworker() {} // Destructor const string& getName() const{ return name; } void setName( const string& n){ name = n; } virtual void display() const; virtual double income() const = 0; virtual Coworker& operator=(const Coworker&); }; #endif
Note |
The virtual operator function for the assignment will be
described in the section on "Virtual Assignments."
|
Motivation
Virtual methods are declared in the base class to ensure
that they are available in any derived classes via the common class interface.
It may happen that they rarely perform any useful tasks in the base class. For
example, a destructor in a base class does not need to perform any explicit
cleaning-up operations.
In this case, of course, you can define a virtual dummy
method whose address is entered in the VMT of the base class. However, this
creates op-code for a function that should never be called. It makes more sense
not to define a function like this. And this is where C++ steps in and gives you
the opportunity of declaring pure virtual methods.
Declaration
When a pure virtual method is declared, the method is
identified by adding the expression = 0.
Example:
virtual void demo()=0; // pure virtual
This informs the compiler that there is no definition of the
demo() method in the class. A NULL pointer is then
entered in the virtual method table for the pure virtual method.
The Base Class Coworker
The opposite page shows a definition of the Coworker class, which was designed to represent human
resources data for a company. The class is used as a base class for various
employees, blue-collar, white-collar, and freelancers.
To keep things simple the Coworker class
has only a name as a data member. However, it could also contain the address of
an employee, or the division where the employee works.
The Coworker class does not comprise
data members to represent an employee's salary. It makes more sense to store
data like this in derived classes where the hourly wage and number of hours
worked by a blue-collar worker and the monthly salary for a white-collar worker
are also defined. The income() method is therefore not
defined for the base class and can be declared as a pure virtual
method.
0 Comments