Friends and Overloaded Operators

Similar documents
Friends and Overloaded Operators

CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

Lecture 7. Log into Linux New documents posted to course webpage

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

More class design with C++ Starting Savitch Chap. 11

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES IV

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

CS 247: Software Engineering Principles. ADT Design

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

W3101: Programming Languages C++ Ramana Isukapalli

Friend Functions, Inheritance

Ch 8. Operator Overloading, Friends, and References

AN OVERVIEW OF C++ 1

Classes and Data Abstraction. Topic 5

Dot and Scope Resolution Operator

Programming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

Object Oriented Design

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Introduction Of Classes ( OOPS )

Fundamentals of Programming Session 24

Introduction to Programming session 24

FRIEND FUNCTIONS IN CPP

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

ADTs & Classes. An introduction

Overloading Operators in C++

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Short Notes of CS201

Object-Oriented Programming (OOP) Fundamental Principles of OOP

PIC 10A. Lecture 15: User Defined Classes

CS201 - Introduction to Programming Glossary By

And Even More and More C++ Fundamentals of Computer Science

Introduction to Classes

Object Oriented Design

Chapter 10 Defining Classes

PIC 10A. Lecture 17: Classes III, overloading

Object Oriented Programming COP3330 / CGS5409

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

CMSC 202 Midterm Exam 1 Fall 2015

Chapter 6 Structures and Classes. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

clarity. In the first form, the access specifier public : is needed to {

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Classes: A Deeper Look. Systems Programming

CSC1322 Object-Oriented Programming Concepts

Come and join us at WebLyceum

Fast Introduction to Object Oriented Programming and C++

EL2310 Scientific Programming

2. Functions I: Passing by Value

Cpt S 122 Data Structures. Introduction to C++ Part II

Ch 6. Structures and Classes

Introduction to C++ Friends, Nesting, Static Members, and Templates Topic #7

CS1004: Intro to CS in Java, Spring 2005

What does it mean by information hiding? What are the advantages of it? {5 Marks}

Implementing an ADT with a Class

Object-Oriented Design (OOD) and C++

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

CS304 Object Oriented Programming Final Term

Question: How can we compare two objects of a given class to see if they are the same? Is it legal to do: Rectangle r(0,0,3,3);,, Rectangle s(0,0,4,4)

NAMESPACES IN C++ You can refer the Programming with ANSI C++ by Bhushan Trivedi for Understanding Namespaces Better(Chapter 14)

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

Recharge (int, int, int); //constructor declared void disply();

Classes: A Deeper Look

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

Question 1 Consider the following structure used to keep employee records:

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES III

Classes and Objects in C++

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Inheritance, and Polymorphism.

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Abstraction in Software Development

OBJECTS. An object is an entity around us, perceivable through our senses. Types of Object: Objects that operate independently.

Chapter 4. Defining Classes I

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Software Design and Analysis for Engineers

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

Comp151. Generic Programming: Container Classes

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

III. Classes (Chap. 3)

OBJECT ORIENTED PROGRAMMING USING C++

CSCI-1200 Data Structures Fall 2018 Lecture 3 Classes I

Chapter 17 - C++ Classes: Part II

EL2310 Scientific Programming

Module 7 b. -Namespaces -Exceptions handling

Transcription:

Friend Function Friends and Overloaded Operators Class operations are typically implemented as member functions Some operations are better implemented as ordinary (nonmember) functions CSC 330 OO Software Design 2 A friend function is a function that is not a member of a class but has access to the class's private and protected members. Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class's scope, and they are not called using the member-selection operators (. and >) unless they are members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It is not affected by the access control keywords. CSC 330 OO Software Design 3 // Example 1: friend_functions.cpp #include <iostream> using namespace std; class Point friend void ChangePrivate( Point & ); Point( ) : mi(0) void PrintPrivate( )cout << mi << endl; int mi; ; void ChangePrivate ( Point &i ) i.mi++; int main() Point spoint; spoint.printprivate( ); ChangePrivate(sPoint); spoint.printprivate( ); CSC 330 OO Software Design 4 // Example 2:Friends can access private members of a class. #include <iostream.h> class Count friend void setx( Count &, int ); // friend declaration Count() x = 0; // constructor void print() const cout << x << endl; // output int x; // data member ; // Can modify private data of Count because // setx is declared as a friend function of Count void setx( Count &c, int val ) c.x = val; // legal: setx is a friend of Count // Example 2 cont d: main program int main() Count counter; cout << "counter.x after instantiation: "; counter.print(); cout << "counter.x after call to setx friend function: "; setx( counter, 8 ); // set x with a friend counter.print(); return 0; CSC 330 OO Software Design 5 CSC 330 OO Software Design 6 1

Program Example: An Equality Function The DayOfYear class can be enhanced to include an equality function An equality function tests two objects of type DayOfYear to see if their values represent the same date Two dates are equal if they represent the same day and month Declaration of The equality Function We want the equality function to return a value of type bool that is true if the dates are the same The equality function requires a parameter for each of the two dates to compare The declaration is bool equal(dayofyear date1, DayOfYear date2); Notice that equal is not a member of the class DayOfYear CSC 330 OO Software Design 7 CSC 330 OO Software Design 8 Defining Function equal Using The Function equal The function equal, is not a member function It must use public accessor functions to obtain the day and month from a DayOfYear object equal can be defined in this way: bool equal(dayofyear date1, DayOfYear date2) return ( date1.get_month( ) == date2.get_month( ) && date1.get_day( ) == date2.get_day( ) ); The equal function can be used to compare dates in this manner if ( equal( today, bach_birthday) ) cout << "It's Bach's birthday!"; A complete program using function equal is found in CSC 330 OO Software Design 9 CSC 330 OO Software Design 10 Is equal Efficient? Function equal could be made more efficient Equal uses member function calls to obtain the private data values Direct access of the member variables would be more efficient (faster) A More Efficient equal As defined here, equal is more efficient, but not legal bool equal(dayofyear date1, DayOfYear date2) return (date1.month = = date2.month && date1.day = = date2.day ); The code is simpler and more efficient Direct access of private member variables is not legal! CSC 330 OO Software Design 11 CSC 330 OO Software Design 12 2

Declaring A Friend Friend Functions The function equal is declared a friend in the abbreviated class definition here class DayOfYear friend bool equal(dayofyear date1, DayOfYear date2); // The rest of the public members // the private members ; Friend functions are not members of a class, but can access private member variables of the class A friend function is declared using the keyword friend in the class definition A friend function is not a member function A friend function is an ordinary function A friend function has extraordinary access to data members of the class As a friend function, the more efficient version of equal is legal CSC 330 OO Software Design 13 CSC 330 OO Software Design 14 Using a Friend Function A friend function is declared as a friend in the class definition A friend function is defined as a nonmember function without using the "::" operator A friend function is called without using the '.' operator Friend Declaration Syntax The syntax for declaring friend function is class class_name friend Declaration_for_Friend_Function_1 friend Declaration_for_Friend_Function_2 Member_Function_Declarations Private_Member_Declarations ; CSC 330 OO Software Design 15 CSC 330 OO Software Design 16 Choosing Friends How do you know when a function should be a friend or a member function? In general, use a member function if the task performed by the function involves only one object In general, use a nonmember function if the task performed by the function involves more than one object Choosing to make the nonmember function a friend is a decision of efficiency and personal taste friend Functions A class's private members are accessible only to its methods and its friend functions. A class's protected members are accessible only to methods in its class hierarchy and its friend functions. To make a function f a friend of class C, we declare f within C's declaration using the keyword friend: class C // friend int f ( ); // friend function // CSC 330 OO Software Design 17 CSC 330 OO Software Design 18 3

friend Functions and friend Classes friend function of a class is defined outside that class s scope but has the right to access private and protected members of the class. A function or an entire class may be declared to be a friend of another class. To declare ClassTwo as a friend of class ClassOne place friend class ClassTwo in the declaration for ClassOne friendship is granted not taken Discussions Because f is not a method, the declaration serves only to give f access rights to C's private and protected members; thus, the declaration may be placed within the private, protected, or public part of the declaration of class C. Because a friend function is not a C++ method, yet has access to C's private and protected members, a friend function violates a strict interpretation of object-oriented principles. Note: It is recommend to use friend functions only in operator overloading. CSC 330 OO Software Design 19 CSC 330 OO Software Design 20 friend Functions cont d class Complex Complex( ); // default Complex( double ) ; // real given Complex( double, double ) ; // both given void write( ) const; // friend functions friend Complex operator+( const Complex&, const Complex& ) ; friend Complex operator-( const Complex&, const Complex& ) ; friend Complex operator*( const Complex&, const Complex& ) ; friend Complex operator/( const Complex&, const Complex& ) ; double real; double imag; ; Implementation File // Complex + as top-level friend Complex operator+( const Complex& t, const Complex& u ) return Complex( t.real + u.real, t.imag + u.imag ) ; // Complex - as top-level friend Complex operator-( const Complex& t, const Complex& u ) return Complex( t.real - u.real, t.imag - u.imag ) ; // Complex * as top-level friend Complex operator*( const Complex& t, const Complex& u ) return Complex( t.real * u.real - t.imag * u.imag, t.imag * u.real + t.real * u.imag ) ; // Complex / as top-level friend Complex operator/( const Complex& t, const Complex& u ) double abs_sq = u.real * u.real + u.imag * u.imag; return Complex( (t.real * u.real + t.imag * u.imag)/abs_sq, (t.imag * u.real - t-real * u.imag)/abs_sq); CSC 330 OO Software Design 21 CSC 330 OO Software Design 22 Rules for Overloading Operators When overloading an operator, at least one argument must be of the class type. You cannot create a new operator. All you can do is overload existing operators such as +, -, *, /, %, etc. You cannot change the number of arguments that an operator takes. For example, you cannot change % from a binary to a unary operator or change ++ from a unary to a binary operator. Rules for Overloading Operators cont d You cannot change the precedence of an operator. An overloaded operator has the same precedence as the ordinary version of the operator. For example, x * y + z always means (x * y) + z, even if x, y and z are objects. The following operators cannot be overloaded: the dot operator (.), the scope resolution operator (::), and the operators.* and?:. An overloaded operator can be a friend of the class or a member of the class. If you overload the assignment operator (=), it must be a member of the class, not a friend. CSC 330 OO Software Design 23 CSC 330 OO Software Design 24 4

Discussions Friendship (i.e., using the friend keyword) is a complex and dangerous topic for various reasons: Friendship, when applied to program design, is an escape mechanism allowing us to circumvent the principles of encapsulation and data hiding. The use of friends should therefore be minimized to situations where they can be used naturally. If friends are used, realize that friend functions or classes become implementation dependent on the classes declaring them as friends. Once the internal organization of the data of a class declaring friends changes, all its friends must be recompiled (and possibly modified) as well. Therefore, as a rule of thumb: don't use friend functions or friend classes. Discussions cont d Discussions cont d Should be used infrequently! Ordinary function (not member function) that has access to private members of class Specify friends in the class prototype (with keyword friend) Do not use dot operators when call (because ordinary function) Do not use scope resolution when define (because not member of class) At least one parameter should be of the class type Only reason for a friend: make function definition simpler and more efficient. Could accomplish same task using accessor/selector functions. CSC 330 OO Software Design 25 CSC 330 OO Software Design 26 5