Friend Functions. Problem u Assuming two Complex objects u How would one add two numbers? W + X Complex operator+(const Complex& w, const Complex& x);

Slides:



Advertisements
Similar presentations
Operator overloading redefine the operations of operators
Advertisements

Class and Objects.
Chapter 14: Overloading and Templates
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Function Overloading Can enables several function Of same name Of different sets of parameters (at least as far as their types are concerned) Used to create.
1 Lab Session-XII CSIT121 Fall 2000 b Namespaces b Will This Program Compile ? b Master of Deceit b Lab Exercise 12-A b First Taste of Classes b Lab Exercise.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
1 Building Classes (the "++" in C++) (Chapter 14) Representing More Complex Objects.
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
Chapter 12: Adding Functionality to Your Classes.
CMSC 202 Lesson 12 Operator Overloading II. Warmup  Overload the + operator to add a Passenger to a Car: class Car { public: // some methods private:
CSC241 Object-Oriented Programming (OOP) Lecture No. 10.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
1 3. More About Data Structures and ADTs: C++ Data types (Read §3.1 & §3.2) C++ types an be classified as: Fundamental (or simple or scalar): A data object.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Operator Overloads Part2. Issue Provide member +(int) operator Rational + int OK int + Rational Error.
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
Operator Overloading Operator Overloading allows a programmer to define new uses of the existing C/C++ operator symbols. –useful for defining common operations.
Computer Science Department CPS 235 Object Oriented Programming Paradigm Lecturer Aisha Khalid Khan Operator Overloading.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
1 const and this Ying Wu Electrical Engineering & Computer Science Northwestern University EECS 230 Lectures Series.
Practice Building Classes Modeling Objects. Problem Write a program that computes the Dean’s List (full-time students whose GPA 3.0), using a student.
Console Programs Console programs are programs that use text to communicate with the use and environment – printing text to screen, reading input from.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
CS Object Oriented Programming Using C++
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
OPERATOR OVERLOADING WEEK 4-5 CHAPTER 19. class Money {private:int lira; int kurus; public: Money() {}; Money(int l, int k) { lira=l+ k/100; kurus=k%100;
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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
CS Class 19 Today  Practice with classes Announcements  Turn in algorithm for Project 5 in class today  Project 5 due 11/11 by midnight – .
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
Operator Overloading Chapter Objectives You will be able to Add overloaded operators, such as +,-, *, and / to your classes. Understand and use.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
Class Operations Creating New Types. Review Last time, we began building, a class to allow us to model temperatures: Last time, we began building Temperature,
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Operator Overloading.
Andy Wang Object Oriented Programming in C++ COP 3330
Yan Shi CS/SE 2630 Lecture Notes
Chapter 12 Classes and Abstraction
Introduction to C++ (Extensions to C)
Function Overloading Can enables several function Of same name
C++ Templates.
Overloading Operator MySting Example
Java Programming: Guided Learning with Early Objects
Object-Oriented Design (OOD) and C++
Basic Elements of C++.
Chapter Structured Types, Data Abstraction and Classes
More about OOP and ADTs Classes
Basic Elements of C++ Chapter 2.
Operator Overloading; String and Array Objects
Operator Overloading.
Operator Overloading; String and Array Objects
More about OOP and ADTs Classes
C++ types an be classified as: Fundamental (or simple or scalar):
COP 3330 Object-oriented Programming in C++
Chapter 14 Object-Oriented Software Development
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Presentation transcript:

Friend Functions

Problem u Assuming two Complex objects u How would one add two numbers? W + X Complex operator+(const Complex& w, const Complex& x); Whose member function is it? W? X? Whose data elements are changed? W? X? Neither; The operation is outside both W and X A similar operation:cout << W;

Solution: u A "compromise" mechanism –Class granting non-member function permission to access its data members. u By –Declaring non-member function within class –Preceding its declaration with keyword friend.

Friend Functions u not member functions of class X u have access to data members in class X u named as a friend in class X’s header u defined in class X’s implementations file u "outside" an object –When friend function operates on an object it receives the object via a parameter.

Friend functions  declared within class (prepend friend ) friend int operator< (const Strings& S1, const Strings& S2);  defined in implementation file (no friend, no ::) int operator< (const Strings& S1, const Strings& S2) u See friend/strings.h & strings.cpp

19. Differentiate among member functions, global functions and friend functions. u Virtual functions must be members u operator>> & operator<< are never members u Only non-member functions get their type conversions on their left-most argument Rational r = 2 * Rational(3,4); operarator* must be Friend or auxiliary function u Everything else should be member functions

Friend example /***** I/O Functions *****/ /* --- ostream output Receives: An ostream Out and a Time object T Output: data members of Time object in standard format. Passes back:ostream Out with T inserted Return value: Out *************************************************/ friend ostream& operator<<(ostream& Out, const Time& T); Definition in Time.cpp remains unchanged.

Overloading Output for Objects How could we output an object using cout << "We'll be eating at " << MealTime << endl; instead of cout << "We'll be eating at " ; MealTime.PrintTime(); cout << endl;

A First Attempt: Put new function in Time.h /***** I/O Functions ******/ /* --- ostream output Receives: An ostream Out and a Time object T Output: The data members of a Time object in standard format. Passes back: The ostream Out with T inserted Return value: The ostream Out*/ ostream& operator<<(ostream& Out, const Time& T); // We're not finished with this declaration // Note: first use of a Time object as a parameter

Place definition in Time.cpp //----- Function to implement ostream output ---- ostream& operator<<(ostream& Out, const Time& T) { Out << T.Hour_ << ':' << (T.Minute_ < 10 ? "0" : "") << T.Minute_ << ' ' << T.AMorPM_ << ".M. (" << (T.MilTime_ < 100 ? "0" : "") << T.MilTime_ << " mil. time)”; return Out; }

Problem u cout << MealTime; << is a function call with two actual params: cout, MealTime u ostream& operator<<(ostream& Out, const Time& T); –(assuming defined as a member function in Time.cpp) –is a function of three parameters: Out, T, and MealTime object (implicitly)

u All member functions receive the object as an implicit parameter. MealTime.Set(5,30,’P’); // a function call with 3 actual params + 1 param passed implicitly (MealTime) void Time::Set(unsigned Hours, unsigned Mins, char AMPM) // a function heading with 3 formal params + 1 implicit formal param (a Time obj)

Compiler error u Overloaded function will not to compile –an overloaded operator definition –cannot change the number of operands an operator takes Compiling TIME.CPP: Error TIME.H 84: 'Time::operator <<(ostream &,const Time &)' must be declared with one parameter Compiler only wants the ostream, it will get the Time from the class in which it is imbedded.

Output example Time MealTime, BedTime(11, 30, 'P');... MealTime.Set(5, 30, 'P'); cout << "Eat at " << MealTime << "\nand sleep at " << BedTime; Execution: Eating at 5:30 P.M. (1730 mil. time) and sleep at 11:30 P.M. (2330 milt time)

Time Class Input: In Time.h, declare operator>>( ) as a friend function: /* --- istream input Receives:An istream In and a Time object T Input:Values for the data members of T. Passes back:istream In with values removed T with values stored in data members Return value:In Note: Input times in format hh:mm xM ***************************************************/ friend istream& operator>>(istream& In, Time& T);

Add to Time.cpp //----- Function to implement istream input ---- istream& operator>>(istream& In, Time& T) { int Hours, Minutes; char Ch,// gobbles up extra characters AMPM; In >> Hours >> Ch >> Minutes >> AMPM >> Ch; T.Set(Hours, Minutes, AMPM); return In; }

Time MealTime, BedTime;... cout << "Enter meal time and bedtime (hh:mm xM): "; cin >> MealTime >> BedTime; cout << "We'll be eating at '' << MealTime << endl; cout << "We'll hit the hay at " << BedTime << endl; Execution: Enter meal time and bedtime (hh:mm xM): 5:30 PM 11:30 PM We'll be eating at 5:30 P.M. (530 mil. time) We'll hit the hay at 11:30 P.M. (2330 milt time) Enter meal time and bedtime (hh:mm xM): 5:30 PM 12:15 AM We'll be eating at 5:30 P.M. (530 mil. time) We'll hit the hay at 12:15 A.M. (015 mil. time)

Class Scope Rule: u Members of a class are local to the class. u Private members can be accessed only within class –by member functions –by friends of the class u Public members class can be accessed outside using dot notation

Summary of our Time Class: u OperationName (ThingsNeeded ) --> (ThingsProduced) u Constructors –Constructor: () --> Time –Constructor: (Hours, Minutes, AMPM) --> Time –Set(Time, Hours, Minutes, AMPM) --> Time u Extractors: –Hour(Time) --> Integer –Minute(Time) --> Integer –AMorPM(Time) --> Character –MilTime: (Time) --> Integer u Input/Output: –Output: (ostream,Time) --> ostream –Input: (istream,Time) --> (Time, istream)

Adding Relational Operator: < Less-than: (Time, Time) --> Boolean Receives: Two Time objects Returns: True if first Time object is less than second; false otherwise.

Is operator< a member function? Does it belong inside the Time class? –it can operate on a Time object that contains it Does it belong outside the class? –it can operate on any Time object Answer: The latter. Not a member function.

Is operator< a friend function? Does it need access to data members? Answer: Yes.

Add to Time.h: /***** Relational operators *~***/ /* --- operator< determines if one Time is less than another Time Receive: Times T1 and T2 Return: True (1) if T1 < T2, false (O) otherwise. */ friend short operator<(const Time& T1, const Time& T2) { return (Tl.MilTime_ < T2.MilTime_); }; Because of simplicity of this function we put it its definition in Time.h.

Adding Advance Function u Advance: (Time, Hours, Minutes) --> Time –Increments Time object by Hours / Minutes u Should it be a member function? –Does it belong inside the Time class –from which it can operate on the Time object that contains it? u Answer: Yes

Add to Time.h: /***** Increment operator *****/ /* --- Advance() increments a Time by a specified value. Receive: Hours, the number of hours to add Minutes, the number of minutes to add Return: The Time object containing this function with its data members incremented by these values. */ void Advance(unsigned Hours, unsigned Minutes);

Advance ( ) increments MilTime_ and converts military time to corresponding standard time and sets Hour_, Minute_, and AMorPM_. //----- Function to implement Advance() void Time::Advance(unsigned Hours, unsigned Minutes) { MilTime_ += 100 * Hours + Minutes; unsigned MilHours = MilTime_ / 100, MilMins = MilTime_ % 100; MilHours += MilMins / 60; MilMins %= 60; MilHours %= 24; MilTime_ = 100 * MilHours + MilMins; ToStandard(MilTime_, Hour_, Minute_, AMorPM_); }

ToStandard( ) Conversion from military to standard time may be useful in other operations We add another utility function: ToStandard ( ) a counterpart to ToMilitary():

Add declaration & def. to Time.cpp void ToStandard(unsigned MilTime, unsigned& Hours, unsigned& Minutes, char& AMPM); /*--- ToStandard converts military time to standard. Receive: A military time MilTime Return: Corresponding std time, Hours, Mins, AMPM */ void ToStandard(unsigned MilTime, unsigned& Hours, unsigned& Minutes, char& AMPM) { Hours = (MilTime / 100) % 12; if (Hours == 0) Hours = 12; Minutes = MilTime % 100; AMPM = (MilTime / 100) < 12 ? 'A' : 'P'; }

Testing cout << "Meal time < Bed time? " << (Mealtime < BedTime ? "TRUE\n" : "FALSE\n"); MealTime.Advance(5,15); cout << "New meal time " << MealTime << endl; cout << "Meal time < Bed time? "; << (Mealtime < BedTime ? "TRUE\n" : "FALSE\n"); Execution: Enter meal time and bedtime (hh:mm xM): 6:00 PM 11:00 PM We'll be eating at 6:00 P.M. (1800 mil. time) We'll hit the hay at 11:00 P.M. (2300 mil. time) Meal time < Bed time? TRUE New meal time 11:15 P.M. (2315 milt time) Meal time < Bed time? FALSE

More to come? u Possible additions v remaining relational operators v ++ operator v = (in place of set ( ) ) v + v += (in place of Advance ( ) )