10 Defining Classes

“The time has come,” the Walrus said,

“To talk of many things:

Of shoes—and ships—and sealing wax—

Of cabbages—and kings—”

LEWIS CARROLL, Through the Looking-Glass

Introduction

In Chapter 6 you learned how to use classes and objects, but not how to define classes. In this chapter we will show you how to define your own classes. A class is a data type. You can use the classes you define in the same way you use the predefined data types, such as int, char, and ifstream. However, unless you define your classes the right way, they will not be as well behaved as the predefined data types. Thus, we spend a good deal of time explaining what makes for a good class definition and give you some techniques to help you define your classes in a way that is consistent with modern programming practices.

Before we introduce classes, we will first present structures (also known as structs). When used in the way we present them here, a structure is a kind of simplified class and structures will prove to be a stepping-stone to understanding classes.

Prerequisites

This chapter uses material from Chapters 2 through 6.