39
1 Using Classes Using Classes Object-Oriented Object-Oriented Programming Using C++ Programming Using C++ Second Edition Second Edition 5

1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

Embed Size (px)

Citation preview

Page 1: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

11

Using ClassesUsing Classes

Object-Oriented Programming Object-Oriented Programming Using C++Using C++

Second EditionSecond Edition

5

Page 2: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

22

ObjectivesObjectives• In this chapter, you will learn:

• How to define a class

• How to include declaration and implementation sections within classes

• How and when to use public and private access modifiers in class definitions

• How to use private functions

• How to use the scope resolution operator with class fields and functions

• About the use of static variables

• About the this pointer

5

Page 3: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

33

Creating Classes with Declaration Creating Classes with Declaration and Implementation Sectionsand Implementation Sections

• Classes provide a convenient way to group related data

• The Student class is an abstract data type (ADT)• Student is a type you define, as opposed to types

like char and int that are defined by C++• One advantage of creating the Student class is that

when you create a Student object, you automatically create all the related Student fields

5

F5-1.cpp

Page 4: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

44

Creating Classes with Declaration Creating Classes with Declaration and Implementation Sectionsand Implementation Sections

• Another advantage is the ability to pass a Student object into a function, or receive a Student object from a function as a returned value, and automatically pass or receive all the individual fields that each Student contains

• The first step to creating a class involves determining the attributes of an object, and subsequently dealing with the object as a whole

5

Page 5: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

55

Encapsulating Class Encapsulating Class ComponentsComponents

• Just as the internal components of a radio are hidden, when you write a program and create a class name for a group of associated variables, you hide, or encapsulate, the individual components

• Sometimes you want to change the state of some components, but often you want to think about the entry as a whole and not concern yourself with the details

5

Page 6: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

66

Designing ClassesDesigning Classes

• You can think of the built-in scalar types of C++ as classes

• You do not have to define those classes; the creators of C++ have already done so

• For most object-oriented classes, then, you declare both fields and functions

• You declare a function by writing its prototype, which serves as the interface to the function

5

Page 7: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

77

Designing ClassesDesigning Classes

• When you declare a class with a function definition, you then create an object of that class, the object possesses more than access to each field—it also possesses access to the function

5

Page 8: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

88

Implementing Implementing MemberMember Functions Functions

• After you create a member function’s prototype, you still must write the actual function

• When you construct a class, you create two parts

– The first part is a declaration section, which contains the class name, variables (attributes), and function prototype

– The second part create is an implementation section, which contains the functions themselves

5

Page 9: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

99

Student Class That Includes Student Class That Includes One Function Definition One Function Definition

and Implementationand Implementation

5

Page 10: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

1010

Implementing Class FunctionsImplementing Class Functions5

Page 11: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

1111

Data Hiding and EncapsulationData Hiding and Encapsulation

• Object-oriented programmers strive to make their classes similar to real-world objects, which usually do not provide access to their inner workings; access is available only to the interface

• One technique programmers use to provide more complete object encapsulation is to make object’s data private

• One major asset of object-oriented programming is that the information hiding can be accomplished more completely than it is with the procedures used in procedural programs

5

Page 12: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

1212

Data Hiding and EncapsulationData Hiding and Encapsulation

• Traditional procedural languages do not allow data to be declared as private; object-oriented languages do

• In C++, data hiding means that you can make data members of a class inaccessible to functions that are not part of that class

• Within a C++ class, you accomplish data encapsulation by making the data private instead of public

5

Page 13: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

1313

Data Hiding and EncapsulationData Hiding and Encapsulation

• A problem arises if you try to run the program shown in Figure 5-4 and you use the new Student class shown in Figure 5-7

• When you compile the program, you receive error messages indicating that the fields idNum, lastName, and gradePointAverage are inaccessible

5

Page 14: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

1414

Using Public Functions to Using Public Functions to Alter Private DataAlter Private Data

• You gain a major advantage when you make a data field private

• Once you create a class, including writing and debugging all of its member functions, outside functions can never modify or erroneously use the private member data of any object in the class

• When you create and test a class, and store its definition in a file, programs that use the definition can be prevented from using member data incorrectly

5

Page 15: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

1515

Using Public Functions to Using Public Functions to Alter Private DataAlter Private Data

• If a private member of your Student class, such as idNum, must be a four-digit number, or if you require that the idNumber always be preceded by a pound sign, functions that are not a member of your class can never change those rules (either intentionally or by accident)

5

Page 16: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

1616

Using Public Functions to Using Public Functions to Alter Private DataAlter Private Data

• To setLastName() function shown in Figure 5-9 is a member of the Student class

• You can determine this because the class header contains the Student class name and the scope resolution operator

5

Page 17: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

1717

Using Public Functions to Using Public Functions to Alter Private DataAlter Private Data

• When you use the setIdNum() function with an object like aJunior, you are assured that aJunior receives a valid idNum

• Figure 5-11 shows how the setGradePointAverage() function can be written to accept a double argument and assure that the argument is no more than 4.0 before assigning it to any Student’s gradePointAverage field

5

Page 18: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

1818

Using a Complete ClassUsing a Complete Class

• Figure 5-12 shows the entire Student class, all its member functions, and a short program that uses the class

5

EX5-1

Page 19: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

1919

Using Private FunctionsUsing Private Functions

• Not all function are public

• When you think of real-world objects, such as kitchen appliances, there are many public functions you control through an interface: adjusting the temperature, etc.

5

EX5-2

Page 20: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

2020

Using Private FunctionsUsing Private Functions5

Page 21: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

2121

Considering Scope When Considering Scope When Defining Member FunctionsDefining Member Functions

• There are circumstances when the scope resolution operator is required with a class field name

• Whenever there is a conflict between local and class variable names, you must use the scope resolution operator to achieve the results you want

• The member variable with the same name is hidden unless you use the scope resolution operator

5

Page 22: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

2222

Considering Scope When Considering Scope When Defining Member FunctionsDefining Member Functions

5

In the second function, idNum refers to only the function’s local variable named idNum

Page 23: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

2323

Using Static Class MembersUsing Static Class Members

• A C++ object is an instantiation of a class that can contain both data members and methods

• When you create an object, a block of memory is set aside for the data members

• Sometimes every instantiation of a class requires the same value

5

Page 24: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

2424

Using Static Class MembersUsing Static Class Members

• To avoid a waste, you declare the athletic fee variable as static, meaning that it is shared by all the instances

• A class variable that you declare to be static is the same for all objects that are instantiations of the class

• Static variables are sometimes called class variables because they do not belong to a specific object; they belong to the class

5

Page 25: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

2525

Defining Static Data MembersDefining Static Data Members

• Because it uses only one memory location, a static data member is defined (given a value) in a single statement outside the class definition

• Most often this statement appears just before the class implementation section

5

Page 26: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

2626

A Class That Contains a Static A Class That Contains a Static AthleticFee FieldAthleticFee Field

5 Ex5-3

•Even though each Student declared in the program has a unique ID number, all Student objects share the athletic fee, which was assigned a value just once

Page 27: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

2727

Defining Static Data MembersDefining Static Data Members

• A static class member exists, even when you have not instantiated any objects of the class

5

Page 28: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

2828

Using Static FunctionsUsing Static Functions

• In the program, the athleticFee field is public, which is why you can access it directly, as in Student::athleticFee = 139.95;

• If it were private, you would have to use a public function to access the value, as with any other private variable

• You cannot use a static function to access a non-static field because static functions do not receive a pointer to the object that uses the function

• Using the directions on pages 179 to 181 of the textbook, you use a private, static class variable to keep track of how many objects have been initialized

5 Ex5-4

Page 29: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

2929

Using Static FunctionsUsing Static Functions

• You will use a public static function to display the private static variable

5

Page 30: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

3030

Understanding the this PointerUnderstanding the this Pointer

• When you define a class, you include fields and functions

• If the class has one non-static field and one static field such as the Employee class shown in Figure 5-23, and you then declare two Employee objects, you reserve storage for two versions of the non-static field

• However, you store only one version of the static field that every object can use

• C++ does not store member functions separately for each instance of a class

5

Page 31: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

3131

Understanding the this PointerUnderstanding the this Pointer

• One copy of each member function is stored, and each instance of a class uses the same function code

5

Page 32: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

3232

Understanding the this PointerUnderstanding the this Pointer5

Ex5-5

Page 33: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

3333

Understanding the this PointerUnderstanding the this Pointer

• Because only one copy of each function exists, when you call a function, it needs to know which objects to use

• To ensure that the function uses the correct object, you use the object’s name, such as clerk or driver, with the dot operator

• Within the displayValue() function, the address of the object is stored in a special pointer called the this pointer

5

Page 34: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

3434

Understanding the this PointerUnderstanding the this Pointer

• The this pointer holds the memory address of the current object that is using the function

• That is why it is named this—it refers to “this object” as opposed to any other object

• The this pointer also is passed to member functions when they receive additional, explicitly stated arguments

5

Page 35: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

3535

Using the this Pointer ExplicitlyUsing the this Pointer Explicitly

• Within any member function, you can prove that the this pointer exists and that it holds the address of the current object

• You do so by using the this pointer to access the object’s data fields

5

Ex5-6

Page 36: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

3636

Using the Pointer-to-Member Using the Pointer-to-Member OperatorOperator

• The functions operate like those in Figure 5-26, but they use the C++ pointer-to-member operator, which looks like an arrow and is constructed by a programmer by using a dash followed by a right angle bracket (or greater-than sign)

• Any pointer variable that is declared to point to a class object can be used to access individual fields or functions of that class by using the parentheses and the asterisk

5

Page 37: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

3737

Using the Pointer-to-Member Using the Pointer-to-Member OperatorOperator

• In the steps shown on page 185 of the textbook, you explicitly add some references to the this pointer to the Letter class you wrote earlier. You are adding the reference to illustrate how the this pointer works.

5

Ex5-7

Page 38: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

3838

SummarySummary

• Each class you define is an abstract data type, or a group type with its own fields and functions

• A technique programmers use to provide more complete object encapsulation is to make most objects’ data private

• You can make functions private when you want to hide their use from client programs

• You can use the scope resolution operator with class fields and functions

5

Page 39: 1 Using Classes Object-Oriented Programming Using C++ Second Edition 5

3939

SummarySummary

• When you declare a class variable to be static, only one copy of the variable is stored, no matter how many class objects you instantiate

• When you create a class, one copy of each member function is stored

• Polymorphism is the object-oriented program feature that allows the same operation to be carried out differently, depending on the object

5