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

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