Friend Functions.  An ordinary function that is given special access to the private members of a class  NOT a member function of the class  Prototype.

Slides:



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

Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Overloading Operators Overloading operators Unary operators Binary operators Member, non-member operators Friend functions and classes Function templates.
Functions CS 308 – Data Structures. Function Definition Define function header and function body Value-returning functions return-data-type function-name(parameter.
Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
1 By Joaquin Vila Preparedbv Sally Scott ACS 168 Problem Solving Using the Computer Chapter 6 Classes Chapter 6 Classes.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
CSC 107 – Programming For Science. Today’s Goal  Discuss writing & using functions  How to declare them, use them, & trace them  Could write programs.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
1 Problem Solving with C++ The Object of Programming Walter Savitch Chapter 6 Defining Classes and Abstract Data Types Slides by David B. Teague, Western.
1 Fall 2002 ACS 168 Problem Solving Using the Computer Weeks 9 and 10 Structures and Classes Class Diagrams Weeks 9 and 10 Structures and Classes Class.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Coyright © 2008 Pearson Addison-Wesley. All rights reserved. Friends, Overloaded Operators, and Arrays in Classes.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 11 Friends, Overloaded Operators, and Arrays in Classes.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11 Friends, Overloaded Operators, and Arrays in Classes.
CSCI-383 Object-Oriented Programming & Design Lecture 5.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
CSC241 Object-Oriented Programming (OOP) Lecture No. 8.
Chapter 8 Operator Overloading, Friends, and References.
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.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Classes Definition A class is a data type whose variables are objects Object – a variable that has member functions as well the ability to hold.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
C++ Classes and Data Structures Jeffrey S. Childs
1 Problem Solving with C++ The Object of Programming Walter Savitch Chapter 8 Tools for Defining ADTs Slides by David B. Teague, Western Carolina University,
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
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.
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?
L what are executable/non-executable statements l out of the ones below which constructs are executable #include p=3.14; const double PI=3.14; int myfunc(int);
Copyright 2006 Pearson Addison-Wesley, 2008, 2013 Joey Paquet 2-1 Concordia University Department of Computer Science and Software Engineering COMP345.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
Friend Function. 2 Any data which is declared private inside a class is not accessible from outside the class. A non-member function cannot have an access.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 14: More About Classes.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
100 學年度碩士班新生暑期課程 程式設計 Object-Oriented Programming: Part I The Basics of Classes.
CMSC 202 Lesson 8 Classes II. Warmup Declare a class (.h part) named “Cup” It has a data member that says how full it is One method called “Drink” that.
COMP 3000 Object-Oriented Programming for Engineers and Scientists Operator Overloading Dr. Xiao Qin Auburn University
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,
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
CSIS 123A Lecture 1 Intro To Classes Glenn Stevenson CSIS 113A MSJC.
General Updates ● The Wiki is now back up to date. I have also added a working link to the lecture slides online. ● Whenever you notice something missing.
Yan Shi CS/SE 2630 Lecture Notes
COMP 53 – Week Two Operator Overloading.
Structures 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?
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Constructors and Other Tools Dr.
Friends, Overloaded Operators, and Arrays in 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?
11.0 Class parameters, const.
Function Overloading C++ allows us to define functions that have the same name but different sets of parameters This capability can be used to define similar.
Learning Objectives Classes Constructors Principles of OOP
Constructors and Other Tools
Friends, Overloaded Operators, and Arrays in Classes
Operator Overloading, Friends, and References
COP 3330 Object-oriented Programming in C++
CS 144 Advanced C++ Programming February 21 Class Meeting
CMSC 202 Lesson 8 Classes II.
Presentation transcript:

Friend Functions

 An ordinary function that is given special access to the private members of a class  NOT a member function of the class  Prototype is listed in the class definition  Keyword friend goes in front of the prototype

Program to demonstrate the function equal. class DayOfYear { public: DayOfYear(int the_month, int the_day); //Initializes the date according to the arguments. DayOfYear( ); //Initializes the date to January first. void input( ); void output( ); int get_month( ); //Returns the month, 1 for January, 2 for February. int get_day( ); //Returns the day of the month. private: int month; int day; };

bool equal(DayOfYear date1, DayOfYear date2); //Precondition: date1 and date2 have values. //Returns true if date1 and date2 represent the same date, //otherwise returns false. int main( ) { DayOfYear today, bach_birthday(3, 21); cout << "Enter today's date:\n"; today.input( ); cout << "Today's date is "; today.output( ); cout << "J. S. Bach's birthday is "; bach_birthday.output( ); if ( equal(today, bach_birthday)) cout << "Happy Birthday Johann Sebastian!\n"; else cout << "Happy Unbirthday Johann Sebastian!\n"; return 0; } Function call: sends today and bach_birthday This is the prototype for a function defined outside the class. It is NOT a member function, but rather a typical function. This is the prototype for a function defined outside the class. It is NOT a member function, but rather a typical function.

//Function definition for equal bool equal(DayOfYear date1, DayOfYear date2) { return ( date1.get_month( ) == date2.get_month( ) && date1.get_day( ) == date2.get_day( ) ); } //Function definitions for DayOfYear class DayOfYear::DayOfYear(int the_month, int the_day){ month = the_month; day = the_day; } DayOfYear::DayOfYear( ){ month = 1; day = 1; } int DayOfYear::get_month( ){ return month; } Notice there is no scope resolution operator since it is not a member function of the class.

int DayOfYear::get_day( ){ return day; } //Uses iostream: void DayOfYear::input( ){ cout << "Enter the month as a number: "; cin >> month; cout << "Enter the day of the month: "; cin >> day; } //Uses iostream: void DayOfYear::output( ){ cout << "month = " << month << ", day = " << day << endl; }

The equal function must use accessor functions. bool equal(DayOfYear date1, DayOfYear date2){ return ( date1.get_month( ) == date2.get_month( ) && date1.get_day( ) == date2.get_day( ) ); }  Here the function is implemented as a “stand-alone” function.  The problem is, a stand-alone function, defined outside a class, must use accessor functions.  It is possible to allow ordinary functions to have direct access to data members (even though those members are private).  An ordinary function declared as a friend of the class gains the required access.

Friend Functions  An ordinary function declared as a friend of the class gains direct access to private data members without going through member functions.  The class grants friend status by declaring the function with the friend keyword.  When a friend function is defined, you do not use the class name and scope resolution operator as you do with members.

Declaring a function as a friend class DayOfYear Here equal is granted friend status { public: friend bool equal(DayOfYear date1, DayOfYear date2); //Precondition: date1 and date2 have values. //Returns true if date1 and date2 represent the same date; otherwise returns false. DayOfYear(int the_month, int the_day); DayOfYear( ); void input( ); void output( ); int get_month( ); int get_day( ); private: int month; int day; };

Friend vs Regular Function  If the function is listed as a friend in the class definition, the function definition looks like this… bool equal(DayOfYear date1, DayOfYear date2) { return ( date1.month == date2.month && date1.day == date2.day ) }  If the function is NOT listed as a friend in the class definition, the function definition would look like this… bool equal(DayOfYear date1, DayOfYear date2) { return ( date1.get_month( ) == date2.get_month( ) && date1.get_day( ) == date2.get_day( ) ); }

Review of Friend Functions  A friend function of a class is an ordinary (non-member) function that has access granted to private members of a that class.  To make a function a friend of a class list that function prototype in the class with the keyword friend. The prototype may be placed in either the public or the private section of the class; however by convention is often placed first before either.  A friend function is NOT a member function. A friend function is defined and called the same way as any ordinary function.  You do not use the dot operator to call a friend function, and you do not use a class resolution operator in the definition of a friend function.

Consider this code fragment from a mainline function: DayOfYear today; //declaration of an instance of the class cout << “enter today’s date: \n”; today.input(); cout << “There are << (12 - today.get_month()) << “ months left in the year. \n”;  You cannot replace today.get_month() with today.month because month is a private data member.  The function get.month() is a public member function used to access the value stored in the private data member month.  Main does not have direct access because it is not listed as a friend.

Use both Member and Nonmember functions.  Members and friends of a class do similar services for a class.  To clarify whether a given task should be done by a friend or member, consider: Use a member function if the task being performed by the function involves only one object. Use a nonmember function if the task being performed involves more than one object. Example: The function equal involves two objects, so we make it a friend. bool equal(DayOfYear date1, DayOfYear date2){ return ( date1.month = = date2.month && date1.day = = date2.day ); }  Whether member or non-member is not always as simple as this rule suggests.  Clarity and readability is the cardinal rule for this issue.

The const Parameter Modifier  Call-by-value vs. call-by-reference Call-by-value creates second copy of values Call-by-value ensures function cannot change parameters Call-by-reference more efficient for large objects such as classes  For classes use call-by-reference with keyword const  The const modifier allows you to pass a parameter by reference (saving overhead) but guarantees not to change the current value.  The compiler will emit error messages when you compile code that does change the parameter

The const Parameter Modifier Example: Money add(const Money& amount1, const Money& amount2); Here any code written in the implementation of the add function that might change amount1 or amount2 will be marked as an error.

Prototype and Header MUST agree  If you use the const parameter modifier in your prototype in your class, you MUST use the const modifier in exactly the same way in your definition, or you will get errors when you compile your code. Example: class SomeClass { public: void aFunc( const int & aVar, double & bVar); friend int compare(const Date & date1, const Date & date2); }; void SomeClass::aFunc(const int & aVar, double & bVar) { // whatever aFunc does } const in prototype must have const in function definition const in prototype must have const in function definition

Use const with member functions  Use const when member function does not change value of calling object Class SomeClass { void output(ostream & outifle) const; }; void SomeClass::output(ostream & outfile) const { // does output } int main(){ SomeClass ObjA; ObjA.output(outfile); ….. } in application, output function cannot change ObjA function header function prototype

What does const do in each of these cases? const int X = 17; class AClass { public: AClass( ); AClass(int); int aFunc( ) const; int bFunc(const AClass& obj1); private: int i; };

CRC  CRC (for Class, Responsibility, and Collaboration) cards  invented CRC cards in response to a need to document collaborative design decisions