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

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Chapter 11 Separate Compilation and Namespaces. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Separate Compilation.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Class and Objects.
Road Map Introduction to object oriented programming. Classes
Chapter 14: Overloading and Templates
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 11 Separate Compilation and Namespaces Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12A Separate Compilation and Namespaces For classes this time.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
Understanding Friends Object-Oriented Programming Using C++ Second Edition 7.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
IT PUTS THE ++ IN C++ Object Oriented Programming.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Defining New Types Lecture 21 Hartmut Kaiser
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.
Learners Support Publications Classes and Objects.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
CPS120: Introduction to Computer Science Functions.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Chapter 8 Operator Overloading, Friends, and References.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
Chapter 11 Separate Compilation and Namespaces. Learning Objectives Separate Compilation –Encapsulation reviewed –Header and implementation files Namespaces.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Computing and Statistical Data Analysis Lecture 6 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Introduction to classes and objects:
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 7: Introduction to Classes and Objects Starting Out with C++ Early.
CITA 342 Section 1 Object Oriented Programming (OOP)
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345.
Chapter 9 Separate Compilation and Namespaces. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Separate Compilation (9.1)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation and Namespaces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Separate Compilation and Namespaces.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Overloading.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
COMP 3000 Object-Oriented Programming for Engineers and Scientists Operator Overloading Dr. Xiao Qin Auburn University
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
Classes in C++ By: Mr. Jacobs. Objectives  Explore the implications of permitting programmers to define their own data types and then present C++ mechanism.
EGR 2261 Unit 13 Classes Read Malik, Chapter 10.
Structures and Classes
Learning Objectives Pointers as dada members
Classes (Part 1) Lecture 3
Chapter 3: Using Methods, Classes, and Objects
More about OOP and ADTs Classes
Separate Compilation and Namespaces
More about OOP and ADTs Classes
Classes and Objects.
Operator Overloading, Friends, and References
Defining Classes and Methods
Classes and Objects Systems Programming.
SPL – PS3 C++ Classes.
Presentation transcript:

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

2 Objectives 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

Objectives Separate Compilation –Encapsulation reviewed –Header and implementation files Namespaces –using directives –Qualifying names –Unnamed namespaces –Hiding helping functions –Nested namespaces 3

4 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

Friend Functions Nonmember functions –Recall: operator overloads as nonmembers They access data through accessor and mutator functions Very inefficient (overhead of calls) Friends can directly access private class data –No overhead, more efficient So: best to make nonmember operator overloads friends! 5

Friend 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-6

7 How to Declare a Function as 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

8 The Customer Class

9 How to Declare a Function as 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

10 How to Declare a Function as 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

11 How to Declare a Function as 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

12 A main() Program Using the Customer Class Ex6-1.cpp

13 Using a Friend Function to Access 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

14 Using a Friend Function to Access 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

15 Using a Friend Function to Access 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

16 The applyTransaction() Function

Friend Function Uses Operator Overloads –Most common use of friends –Improves efficiency –Avoids need to call accessor/mutator member functions –Operator must have access anyway Might as well give full access as friend Friends can be any function 8-17

Friend 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 18

19 Using 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

20 Using 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

21 Using a Friend Function with Two Classes

22 Using a Friend Function with Two Classes Ex6-2.cpp

23 Using 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

24 Using 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 Ex6-3

25 Two Instances of a Class Using 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

26 Two Instances of a Class Using a Friend You simply create a member function for the CustTransaction class The prototype is: CustTransaction addTransactions (const CustTransaction aPayment);

27 CustTransaction Class with addTransactions() Member Function Ex6-4.cpp

28 Two Instances of a Class Using 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

29 CustTransaction Class a Friend Function Ex6-5.cpp

30 Two Instances of a Class Using 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

31 Making a Friend of a Member 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

32 Making a Friend of a Member 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

33 Definitions of CourseRec and StudentRequest

34 Definitions of CourseRec and StudentRequest

35 Making a Friend of a Member of Another Class Ex6-7.cpp

36 Making a Friend of a Member 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

37 Making a Friend of Another Class 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

Friend 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 38

Separate 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 39

Class Separation Class Independence –Separate class definition/specification Called "interface" –Separate class implementation –Place in two files If implementation changes  only that file need be changed Class specification need not change "User" programs need not change 43

Encapsulation 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 41

Encapsulation 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 to users of class 42

Namespaces 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 43

using 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 44

Namespace std We’ve used namespace std Contains all names defined in many standard library files Example: #include –Places all name definitions (cin, cout, etc.) into std namespace –Program doesn’t know names –Must specify this namespace for program to access names 45

Global Namespace All code goes in some namespace Unless specified  global namespace –No need for using directive –Global namespace always available –Implied "automatic" using directive 46

Multiple 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 47

Specifying 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 48

Creating a Namespace Use namespace grouping: namespace Name_Space_Name { Some_Code } Places all names defined in Some_Code into namespace Name_Space_Name Can then be made available: using namespace Name_Space_Name 49

Creating a Namespace Example Function declaration: namespace Space1 { void greeting(); } Function definition: namespace Space1 { void greeting() { cout << "Hello from namespace Space1.\n"; } } 50 Ex6-9.cpp

using Declarations Can specify individual names from namespace Consider: Namespaces NS1, NS2 exist Each have functions fun1(), fun(2) –Declaration syntax: using Name_Space::One_Name; –Specify which name from each: using NS1::fun1; using NS2::fun2; 51

using 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 52

Qualifying 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 53

Naming Namespaces Include unique string –Like last name Reduces chance of other namespaces with same name Often multiple programmers write namespaces for same program –Must have distinct names –Without  multiple definitions of same name in same scope Results in error 54

Unnamed 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 55

Global vs. Unnamed Namespaces Not same Global namespace: –No namespace grouping at all –Global scope Unnamed namespace: –Has namespace grouping, just no name –Local scope 56

Nested Namespaces Legal to nest namespaces namespace S1 { namespace S2 { void sample() { … } } Qualify names twice: –S1::S2::sample(); 57 Ex6-10.cpp

58 Summary 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

59 Summary 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

Summary 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 60

Summary Namespace definitions are placed inside 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 61