In Chapter 2, we declared all of a program’s variables in its main
function. Variables declared in a function definition’s body are known as local variables and can be used only from the line of their declaration in the function to the closing right brace (}
) of the block in which they’re declared. A local variable must be declared before it can be used in a function. A local variable cannot be accessed outside the function in which it’s declared. When a function terminates, the values of its local variables are lost. (You’ll see an exception to this in Chapter 6 when we discuss static
local variables.)
A class normally consists of one or more member functions that manipulate the attributes that belong to a particular object of the class. Attributes are represented as variables in a class definition. Such variables are called data members and are declared inside a class definition but outside the bodies of the class’s member-function definitions. Each object of a class maintains its own attributes in memory. These attributes exist throughout the life of the object. The example in this section demonstrates a GradeBook
class that contains a courseName
data member to represent a particular GradeBook
object’s course name. If you create more than one GradeBook
object, each will have its own courseName
data member, and these can contain different values.