friend and namespace

61
1 Friends and Namespace Friends and Namespace COSC 1567 COSC 1567 C++ Programming C++ Programming Lecture 6

Upload: nitin-pannicker

Post on 13-Apr-2015

58 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: friend and namespace

11

Friends and NamespaceFriends and Namespace

COSC 1567COSC 1567

C++ ProgrammingC++ Programming

Lecture 6

Page 2: friend and namespace

22

ObjectivesObjectives

• What a friend is• Declare a friend function• Use a friend function with data from two classes• Use a forward reference• Use a friend function with two or more instances

of the same class• bestow friendship on functions that are members

of other classes• Bestow friendship on an entire class

Page 3: friend and namespace

ObjectivesObjectives

• Separate Compilation– Encapsulation reviewed– Header and implementation files

• Namespaces– using directives– Qualifying names– Unnamed namespaces– Hiding helping functions– Nested namespaces

33

Page 4: friend and namespace

44

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

Page 5: friend and namespace

Friend FunctionsFriend Functions

• Nonmember functions– Recall: operator overloads as nonmembers

• They access data through accessor and mutatorfunctions

• Very inefficient (overhead of calls)

• Friends can directly access private class data– No overhead, more efficient

• So: best to make nonmember operatoroverloads friends!

55

Page 6: friend and namespace

Friend FunctionsFriend Functions

• Friend function of a class– Not a member function– Has direct access to private members

• Just as member functions do

• Use keyword friend in front of function declaration– Specified IN class definition– But they’re NOT member functions!

8-8-66

Page 7: friend and namespace

77

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

Page 8: friend and namespace

88

The Customer ClassThe Customer Class

Page 9: friend and namespace

99

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

Page 10: friend and namespace

1010

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

Page 11: friend and namespace

1111

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

Page 12: friend and namespace

1212

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

Ex6-1.cpp

Page 13: friend and namespace

1313

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

Page 14: friend and namespace

1414

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

Page 15: friend and namespace

1515

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

Page 16: friend and namespace

1616

The applyTransaction() The applyTransaction() FunctionFunction

Page 17: friend and namespace

Friend Function UsesFriend Function Uses

• Operator Overloads – Most common use of friends

– Improves efficiency

– Avoids need to call accessor/mutatormember functions

– Operator must have access anyway• Might as well give full access as friend

• Friends can be any function

8-8-1717

Page 18: friend and namespace

Friend Function PurityFriend Function Purity

• Friends not pure?– "Spirit" of OOP dictates all operators and functions be

member functions– Friends violate basic OOP principles

• Advantageous?– For operators: very!– Allows automatic type conversion– Still encapsulates: friend is in class definition– Improves efficiency

1818

Page 19: friend and namespace

1919

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

Page 20: friend and namespace

2020

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

Page 21: friend and namespace

2121

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

Page 22: friend and namespace

2222

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

Ex6-2.cpp

Page 23: friend and namespace

2323

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

Page 24: friend and namespace

2424

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 itselfEx6-3

Page 25: friend and namespace

2525

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

Page 26: friend and namespace

2626

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);

Page 27: friend and namespace

2727

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

FunctionFunction

Ex6-4.cpp

Page 28: friend and namespace

2828

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

Page 29: friend and namespace

2929

CustTransaction Class a Friend FunctionCustTransaction Class a Friend Function

Ex6-5.cpp

Page 30: friend and namespace

3030

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

• Another example

– Create a friend function to compare two Loan objects and determine whether they are equal

– Consider two loans equal if they are for the same amount at the same interest rate

Ex6-6.cpp

Page 31: friend and namespace

3131

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

Page 32: friend and namespace

3232

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

Page 33: friend and namespace

3333

Definitions of CourseRec Definitions of CourseRec and StudentRequestand StudentRequest

Page 34: friend and namespace

3434

Definitions of CourseRec Definitions of CourseRec and StudentRequestand StudentRequest

Page 35: friend and namespace

3535

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

Ex6-7.cpp

Page 36: friend and namespace

3636

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

• Another example: • 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

Ex6-8.cpp

Page 37: friend and namespace

3737

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

Modify ex6-7.cpp

Page 38: friend and namespace

Friend ClassesFriend Classes

• Entire classes can be friends– Similar to function being friend to class– Example:

class F is friend of class C• All class F member functions are friends of C• NOT reciprocated• Friendship granted, not taken

• Syntax: friend class F– Goes inside class definition of "authorizing" class

3838

Page 39: friend and namespace

Separate CompilationSeparate Compilation

• Program Parts– Kept in separate files– Compiled separately– Linked together before program runs

• Class definitions– Separate from "using" programs– Build library of classes

• Re-used by many different programs• Just like predefined libraries

3939

Page 40: friend and namespace

Class SeparationClass Separation

• Class Independence– Separate class definition/specification

• Called "interface"

– Separate class implementation– Place in two files

• If implementation changes only thatfile need be changed

• Class specification need not change• "User" programs need not change

4343

Page 41: friend and namespace

Encapsulation ReviewedEncapsulation Reviewed

• Encapsulation principle:– Separate how class is used by programmer

from details of class’s implementation

• "Complete" separation– Change to implementation NO impact on

any other programs

• Basic OOP principle

4141

Page 42: friend and namespace

Encapsulation RulesEncapsulation Rules

• Rules to ensure separation:

1. All member variables should be private

2. Basic class operations should be:• Public member functions• Friend or ordinary functions• Overloaded operators

Group class definition and prototypes together• Called "interface" for class

3. Make class implementation unavailable tousers of class

4242

Page 43: friend and namespace

NamespacesNamespaces

• Namespace defined:A collection of name definitions– Class definitions– Variable declarations

• Programs use many classes, functions– Commonly have same names– Namespaces deal with this– Can be "on" or "off"

• If names might conflict turn off

4343

Page 44: friend and namespace

using Directiveusing Directive

• using namespace std;– Makes all definitions in std namespace

available

• Why might you NOT want this?– Can make cout, cin have non-standard

meaning• Perhaps a need to redefine cout, cin

– Can redefine any others

4444

Page 45: friend and namespace

Namespace stdNamespace std

• We’ve used namespace std• Contains all names defined in many standard

library files• Example:

#include <iostream>– Places all name definitions (cin, cout, etc.)

into std namespace– Program doesn’t know names– Must specify this namespace for program

to access names

4545

Page 46: friend and namespace

Global NamespaceGlobal Namespace

• All code goes in some namespace

• Unless specified global namespace– No need for using directive– Global namespace always available– Implied "automatic" using directive

4646

Page 47: friend and namespace

Multiple NamesMultiple Names

• Multiple namespaces– e.g., global, and std typically used

• What if name defined in both?– Error– Can still use both namespaces– Must specify which namespace used at

what time

4747

Page 48: friend and namespace

Specifying NamespacesSpecifying Namespaces

• Given namespaces NS1, NS2– Both have void function myFunction()

defined differently{ using namespace NS1; myFunction();}{ using namespace NS2; myFunction();}

– using directive has block-scope

4848

Page 49: friend and namespace

Creating a NamespaceCreating a Namespace

• Use namespace grouping:namespace Name_Space_Name{

Some_Code}

• Places all names defined in Some_Codeinto namespace Name_Space_Name

• Can then be made available:using namespace Name_Space_Name

4949

Page 50: friend and namespace

Creating a Namespace Creating a Namespace ExampleExample

• Function declaration:namespace Space1{

void greeting();}

• Function definition:namespace Space1{

void greeting(){

cout << "Hello from namespace Space1.\n";}

}

5050

Ex6-9.cpp

Page 51: friend and namespace

using Declarationsusing Declarations

• Can specify individual names from namespace

• Consider:Namespaces NS1, NS2 existEach have functions fun1(), fun(2)– Declaration syntax:

using Name_Space::One_Name;– Specify which name from each:

using NS1::fun1;using NS2::fun2;

5151

Page 52: friend and namespace

using Definitions and Declarationsusing Definitions and Declarations

• Differences:

– using declaration• Makes ONE name in namespace available• Introduces names so no other uses of name

are allowed

– using directive• Makes ALL names in namespace available• Only "potentially" introduces names

5252

Page 53: friend and namespace

Qualifying NamesQualifying Names

• Can specify where name comes from– Use "qualifier" and scope-resolution operator– Used if only intend one use (or few)

• NS1::fun1();– Specifies that fun() comes from namespace

NS1

• Especially useful for parameters:int getInput(std::istream inputStream);– Parameter found in istream’s std namespace– Eliminates need for using directive or declaration

5353

Page 54: friend and namespace

Naming NamespacesNaming Namespaces

• Include unique string– Like last name

• Reduces chance of other namespaceswith same name

• Often multiple programmers writenamespaces for same program– Must have distinct names– Without multiple definitions of same name

in same scope• Results in error

5454

Page 55: friend and namespace

Unnamed NamespacesUnnamed Namespaces

• Compilation unit defined:– A file, along with all files #included in file

• Every compilation unit has unnamed namespace– Written same way, but with no name– All names are then local to compilation unit

• Use unnamed namespace to keep things "local"

• Scope of unnamed namespace is compilation unit

5555

Page 56: friend and namespace

Global vs. Unnamed NamespacesGlobal vs. Unnamed Namespaces

• Not same

• Global namespace:– No namespace grouping at all– Global scope

• Unnamed namespace:– Has namespace grouping, just no name– Local scope

5656

Page 57: friend and namespace

Nested NamespacesNested Namespaces

• Legal to nest namespacesnamespace S1{

namespace S2{

void sample(){

…}

}

• Qualify names twice:– S1::S2::sample();

5757

Ex6-10.cpp

Page 58: friend and namespace

5858

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

Page 59: friend and namespace

5959

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

• Bestow friendship on an entire class

– Every function that is a member of the class becomes a friend of the granting class

Page 60: friend and namespace

SummarySummary

• Can separate class definition and implementation separate files– Separate compilation units

• Namespace is a collection of name definitions• Three ways to use name from namespace:

– Using directive– Using declaration– Qualifying

6060

Page 61: friend and namespace

SummarySummary

• Namespace definitions are placedinside namespace groupings

• Unnamed namespace– Used for local name definitions– Scope is compilation unit

• Global namespace– Items not in a namespace grouping at all– Global scope

6161