Chapter 13. Simple Classes

She thinks that even up in heavenHer class lies late and snores.

Cyril Connolly

So far you’ve used simple variables and structures to hold data and functions to process the data. C++ classes allow you to combine data and the functions that use it.

In this chapter you’ll see how a class can improve your code; you’ll implement a simple stack two ways: first using a structure and functions, then using a class.

Stacks

A stack is an algorithm for storing data. Data can be put in the stack using a push operation. The pop operation removes the data. Data is stored in last-in-first-out (LIFO) order.

You can think of a stack as a stack of papers. When you perform a push operation, you put a new paper on top of the stack. You can push as many times as you want; each time the new data goes on top of the stack. You get data out of a stack using the pop operation, which takes the top paper off the stack and gives it to the caller.

Suppose you start with an empty stack and put three elements on it, 4, 5, and 8, using three push operations. The first pop would return the top element, 8. The elements 4 and 5 remain in the stack. Popping again gives you 5. You then push another value, 9, on the stack. Popping twice gives you the numbers 9 and 4, in that order. This is illustrated by Table 13-1.

Table 13-1. Stack operation

Operation

Stack after operation

Push (4)

4

Push (5)

5 4

Push (8)

8 5 4

Pop (returns 8)

5 4

Pop (returns 5)

4

Push (9)

9 4

Pop (returns 9)

4

Pop (returns 4)

<empty>

Designing ...

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.