Interfaces are a company's most valuable resources. Designing an interface takes longer than whipping together a concrete class which fulfills that interface. Furthermore interfaces require the time of more expensive people.
Since interfaces are so valuable, they should be protected from being tarnished by data structures and other implementation artifacts. Thus you should separate interface from implementation.
[ Top | Bottom | Previous section | Next section | Search the FAQ ]
Use an ABC.
[ Top | Bottom | Previous section | Next section | Search the FAQ ]
An abstract base class.
At the design level, an abstract base class (ABC) corresponds to an abstract concept. If you asked a mechanic if he repaired vehicles, he'd probably wonder what kind-of vehicle you had in mind. Chances are he doesn't repair space shuttles, ocean liners, bicycles, or nuclear submarines. The problem is that the term "vehicle" is an abstract concept (e.g., you can't build a "vehicle" unless you know what kind of vehicle to build). In C++, class Vehicle would be an ABC, with Bicycle, SpaceShuttle, etc, being derived classes (an OceanLiner is-a-kind-of-a Vehicle). In real-world OO, ABCs show up all over the place.
At the programming language level, an ABC is a class that has one or more pure virtual member functions. You cannot make an object (instance) of an ABC.
[ Top | Bottom | Previous section | Next section | Search the FAQ ]
A member function declaration that turns a normal class into an abstract class (i.e., an ABC). You normally only implement it in a derived class.
Some member functions exist in concept; they don't have any reasonable
definition. E.g., suppose I asked you to draw a Shape at location
This pure virtual function makes Shape an ABC. If you want, you can think of
the "
Note that it is possible to provide a definition for a pure virtual function, but this usually confuses novices and is best avoided until later.
[ Top | Bottom | Previous section | Next section | Search the FAQ ]
If the class "owns" the object pointed to by the (abstract) base class pointer,
use the Virtual Constructor Idiom in the (abstract)
base class. As usual with this idiom, we declare a pure
virtual
Then we implement this
(Note: the return type in the derived class is intentionally different from the one in the base class.)
Here is the code for derived class Square:
Now suppose that each Fred object "has-a" Shape object. Naturally the
Fred object doesn't know whether the Shape is Circle or a Square or ...
Fred's copy constructor and assignment operator will invoke Shape's
[ Top | Bottom | Previous section | Next section | Search the FAQ ]
E-mail the author
[ C++ FAQ Lite
| Table of contents
| Subject index
| About the author
| ©
| Download your own copy ]
Revised Mar 1, 2006