Skip to Main Content
Practical C++ Programming, 2nd Edition
book

Practical C++ Programming, 2nd Edition

by Steve Oualline
December 2002
Beginner to intermediate content levelBeginner to intermediate
576 pages
14h 6m
English
O'Reilly Media, Inc.
Content preview from Practical C++ Programming, 2nd Edition

Chapter 21. Advanced Classes

The ruling ideas of each age have ever been the ideas of its ruling class.

Karl Marx, Manifesto of the Communist Party

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:

  1. Does all the operations of a typical stack. (In C++ this is called a base class.)

  2. 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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Discovering Modern C++, 2nd Edition

Discovering Modern C++, 2nd Edition

Peter Gottschling

Publisher Resources

ISBN: 0596004192Supplemental ContentErrata Page