Chapter 21. Advanced Classes
The ruling ideas of each age have ever been the ideas of its ruling class.
This chapter discusses derived classes, virtual functions, and virtual classes.
Derived Classes
Suppose we want a stack that allows us to push on three items at a time in addition to performing all usual operations of a stack.[1] If we parse this statement in C++ terms, we discover something significant. We want a stack that:
Does all the operations of a typical stack. (In C++ this is called a base class.)
Expands on this by allowing us to do something more: specifically, push things on in groups of threes. (C++ calls this a derived class.)
Our basic stack is defined in Example 13-2.
We need to define a new expanded stack, which allows us to push multiple items.
We call this an m_stack
. This new
stack does everything a simple stack does but also lets you push three
items on at once. C++ allows you to build new classes on old ones. In
this case we will be building our multiple-push stack (m_stack
) on the existing simple stack
(stack
). Technically we will be
using the class stack
as
a base class to create a new
derived class, the multiple-push stack.
We start by telling C++ that we are creating m_stack
out of stack:
class m_stack: public stack {
The keyword public tells C++ to
make all the public members of stack
accessible to the outside world. If we
declared stack
as private, the public and protected members of stack
would be accessible only ...
Get Practical C++ Programming, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.