1 Understanding Friends Object-Oriented Programming Using C++ Second Edition 7.

Post on 18-Jan-2016

218 views 0 download

transcript

11

Understanding FriendsUnderstanding Friends

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

Second EditionSecond Edition

7

22

ObjectivesObjectives

• In this chapter, you will learn:• What a friend is• How to declare a friend function• How to use a friend function with data from two

classes• How and when to use a forward reference• When to use a friend function with two or more

instances of the same class• How to bestow friendship on functions that are

members of other classes• How to bestow friendship on an entire class

7

33

What Are Friends?What Are Friends?

• A friend function is a function that can access private data members of a class, even though the function itself is not a member of the class

• A friend class is a class whose functions can all access private data members of another class

• A friend function can access private data from a class of which it is not a member, but a friend function cannot be a friend on its own

• The friend relationship is always one-sided

7

44

How to Declare a Function How to Declare a Function as a Friendas a Friend

• The class contains data fields for a customer number and balance

• The class contains three functions; two are members of the class

• The default constructor for the Customer class supplies values for the data fields if none are provided when a Customer object is instantiated

7

55

The Customer ClassThe Customer Class7

66

How to Declare a Function How to Declare a Function as a Friendas a Friend

• As a member of the Customer class, the displayCustomer() function meets the following conditions:

– Requires the class name Customer and the scope resolution operator in the function header

– Must have access to the private fields custNum and balanceDue

– Must be declared in the public section of the class definition, so that a main() program (or any other client function) can use it

7

77

How to Declare a Function How to Declare a Function as a Friendas a Friend

• The function displayAsAFriend() is not a Customer member function

• It must meet the following conditions:

– Cannot use the class name Customer and the scope resolution operator in the function header

– Need not be declared in the public section of the class definition

– Must use the C++ keyword friend in its declaration

7

88

How to Declare a Function How to Declare a Function as a Friendas a Friend

• When any function tries to access an object’s private data member, the compiler examines the list of function prototypes in the class declaration, and one of three things happens:

– The function is found to be a member function, and access is approved

– The function is found to be a friend function, and access is approved

– The function is not found to be a member or a friend, and access is denied; you receive an error message

7

99

A main() Program Using A main() Program Using the Customer Classthe Customer Class

7

Ex7-1

1010

Using a Friend Function to Using a Friend Function to Access Data from Two ClassesAccess Data from Two Classes

• Figure 7-3 shows the definition section of a CustTransaction class

• You might create a CustTransaction object for each customer transaction, such as a purchase of an item, payment on an account, or return of an item

7

1111

Using a Friend Function to Using a Friend Function to Access Data from Two ClassesAccess Data from Two Classes

• If you create a function that performs the payment application operation, you have at least five choices (although four of these are inferior choices):– You can make the balanceDue field in the Customer class

public, and the paymentAmount field in the CustTransaction class public

– If you create a payment application function that is not a member of either the Customer or the CustTransaction class, the function will not have access to the private data fields of either class

7

1212

Using a Friend Function to Using a Friend Function to Access Data from Two ClassesAccess Data from Two Classes

• The choices continued:– If you make the payment application function a member of

the Customer class, the function has access to balanceDue, but not to paymentAmount, which is private within the CustTransaction class

– If you make the payment application function a member of the CustTransaction class, the function has access to paymentAmount, but not to balanceDue, which is private within the Customer class

– You can make the payment application function a friend of both classes

7

1313

The applyTransaction() The applyTransaction() FunctionFunction

7

1414

Using a Forward ReferenceUsing a Forward Reference

• To use the applyTransaction() function as a friend to both the Customer and the CustTransaction class, you must declare the function as a friend within each class

• The declaration of the applyTransaction() function is:friend void applyTransaction(Customer cust, CustTransaction trans);

• You already know you must declare a variable before using it

7

1515

Using a Forward ReferenceUsing a Forward Reference

• You also must declare, or prototype, a function before you use it

• Similarly, a class must be declared before you use it• A forward reference lets the compiler know that the class

exists, and that the details will come later

7

1616

Using a Friend Function Using a Friend Function with Two Classeswith Two Classes

7

1717

Using a Friend Function Using a Friend Function with Two Classeswith Two Classes

7

Ex7-2

1818

Using a Forward ReferenceUsing a Forward Reference

• When two classes refer to each other, you can choose to forward declare either one, and then define the other class first

• The same principle holds true if three, four, or more classes share a friend function that makes reference to all the classes

7

1919

Using a Forward ReferenceUsing a Forward Reference

• In this case you:– Forward declare all the classes except one

– Define the class you did not forward declare, and include the friend function prototype in the class definition

– Define all classes that you did forward declare. The forward declared classes will contain the same friend function prototype as the first class you defined

– Define the friend function itself

• In the set of steps on pages 242 to 244 of the textbook, you define two classes that will be used by a computer repair company

7

2020

Using a Forward ReferenceUsing a Forward Reference

• In the steps shown on pages 244 to 245 of the textbook, you add a main() function to the file

7

Ex7-3

2121

Two Instances of a Class Two Instances of a Class Using a FriendUsing a Friend

• You can use a friend function to access private data members from objects that belong to two different classes

• If you want a function to have access to two or more instances of the same class, you can use either a class member function or a friend function

• You can sum two CustTransaction objects without creating a friend function

7

2222

Two Instances of a Class Two Instances of a Class Using a FriendUsing a Friend

• You simply create a member function for the CustTransaction class

• The prototype is:

CustTransaction addTransactions (const CustTransaction aPayment);

7

2323

CustTransaction Class with CustTransaction Class with addTransactions() Member addTransactions() Member

FunctionFunction

7

Ex7-4

2424

Two Instances of a Class Two Instances of a Class Using a FriendUsing a Friend

• Within addTransactions(), the billingSummary.paymentAmount is set equal to the sum of the invoking object’s (firstTrans) paymentAmount and the passed object’s (secondTrans) payment amount

• A copy of the entire, newly constructed and defined billingSummary is returned to the calling function, where totalTrans receives it

• One way to avoid a subsidiary transaction is to create a friend function to the CustTransaction class

7

2525

CustTransaction Class with CustTransaction Class with addTransactions() addTransactions()

Friend FunctionFriend Function

7

Ex7-5

2626

Two Instances of a Class Two Instances of a Class Using a FriendUsing a Friend

• In the set of steps on pages 250 to 253 of the textbook, you create a friend function to compare two Loan objects and determine whether they are equal

• You consider two loans equal if they are for the same amount at the same interest rate

7

2727

Output of Loan ProgramOutput of Loan Program7

Ex7-6

2828

Making a Friend of a Making a Friend of a Member of Another ClassMember of Another Class

• Classes can bestow friendship on nonmember functions; they also can bestow friendship on functions that are members of other classes

• Consider two classes developed for a college registration system

• One class is named StudentRequest; it holds a student idNum and a course section in which the student requests enrollment

• The other class, named CourseRec, holds information about one section of a course, including a section number, enrollment limit, and current enrollment

7

2929

Making a Friend of a Making a Friend of a Member of Another ClassMember of Another Class

• The student enrollment request example shows a class granting friendship to a single function that is a member of another class

• Creating the class definitions for the preceding example requires three operations:

– Forward declare the class that is granting friendship, because the class that holds the friend will use this class name

– Declare the class containing the function that will be a friend

– Define the class that is granting friendship

7

3030

Definitions of CourseRec Definitions of CourseRec and StudentRequestand StudentRequest

7

3131

Definitions of CourseRec Definitions of CourseRec and StudentRequestand StudentRequest

7

3232

Making a Friend of a Making a Friend of a Member of Another ClassMember of Another Class

7

Ex7-7

3333

Making a Friend of a Making a Friend of a Member of Another ClassMember of Another Class

• In the steps referred to on pages 257 to 260 of the textbook, you write a program that can be used for classroom scheduling

• Two classes of objects are needed: Courses and Rooms• When a Course section is scheduled, a search is made

for a Room that holds the number of students that might enroll

7

Ex7-8.cpp

3434

Making a Friend of Another Making a Friend of Another ClassClass

• To grant friendship to an entire class, construct the class definition simply by writing the keyword friend followed by class and the name of the class

• When you grant friendship to a class, every function that is a member of the class becomes a friend of the granting class

7

Modify ex7-7

3535

SummarySummary

• A friend function is a function that can access private data members of a class, even though the function itself is not a member of the class

• A friend function does not use the class name and the scope resolution operator in the function header

• You can create a function that is a friend to multiple classes

7

3636

SummarySummary

• If you want a function to have access to two or more instances of the same class, you can use either a class member function or a friend function

• Classes can bestow friendship on functions that are members of other classes

• You can bestow friendship on an entire class

• When you grant friendship to a class, every function that is a member of the class becomes a friend of the granting class

7