Abstract base classes
Abstract base classes are something very similar to thePolygon
class in the previous example. They are classes that can only be used as base classes, and thus are allowed to have virtual member functions without definition (known as pure virtual functions). The syntax is to replace their definition by =0
(an equal sign and a zero):An abstract base
Polygon
class could look like this:
|
|
Notice that
area
has no definition; this has been replaced by =0
, which makes it a pure virtual function. Classes that contain at least one pure virtual function are known as abstract base classes.Abstract base classes cannot be used to instantiate objects. Therefore, this last abstract base class version of
Polygon
could not be used to declare objects like:
|
|
But an abstract base class is not totally useless. It can be used to create pointers to it, and take advantage of all its polymorphic abilities. For example, the following pointer declarations would be valid:
|
|
And can actually be dereferenced when pointing to objects of derived (non-abstract) classes. Here is the entire example:
|
| 20 10 |
In this example, objects of different but related types are referred to using a unique type of pointer (
Polygon*
) and the proper member function is called every time, just because they are virtual. This can be really useful in some circumstances. For example, it is even possible for a member of the abstract base class Polygon
to use the special pointerthis
to access the proper virtual members, even though Polygon
itself has no implementation for this function:
|
| 20 10 |
Virtual members and abstract classes grant C++ polymorphic characteristics, most useful for object-oriented projects. Of course, the examples above are very simple use cases, but these features can be applied to arrays of objects or dynamically allocated objects.
Here is an example that combines some of the features in the latest chapters, such as dynamic memory, constructor initializers and polymorphism:
|
| 20 10 |
Notice that the
ppoly
pointers:
|
|
are declared being of type "pointer to
Polygon
", but the objects allocated have been declared having the derived class type directly (Rectangle
and Triangle
).
No comments:
Post a Comment