Chapter 6: UNDERSTANDING FRIENDS AND OVERLOADING OPERATORS

Slides:



Advertisements
Similar presentations
Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - Operator Overloading Outline 8.1 Introduction 8.2 Fundamentals of Operator Overloading 8.3.
Overloading Operators Overloading operators Unary operators Binary operators Member, non-member operators Friend functions and classes Function templates.
Operator Overloading Fundamentals
1 Overloading Operators COSC 1567 C++ Programming Lecture 7.
Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
Rossella Lau Lecture 10, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 10: Operator overload  Operator overload.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 18 - C++ Operator Overloading Outline 18.1Introduction.
Understanding Friends Object-Oriented Programming Using C++ Second Edition 7.
Chapter 15: Operator Overloading
Operator overloading Object Oriented Programming.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
1 Friends and Namespace COSC 1567 C++ Programming Lecture 6.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
Overloading Operators. Operators  Operators are functions, but with a different kind of name – a symbol.  Functions.
1 Overloading Operators Object-Oriented Programming Using C++ Second Edition 8.
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.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
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.
Operator Overloading. Introduction It is one of the important features of C++ language  Compile time polymorphism. Using overloading feature, we can.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
LECTURE LECTURE 13 Operator Overloading Textbook p.203—216 Today: const member functions Overloading Operators Postfix/infix increment.
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;
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Overloading.
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.
Topic 10ARRAYS 1 TOPIC 10 continued l Arrays of objects Arrays.
1 CSC241: Object Oriented Programming Lecture No 08.
1 09/10/04CS150 Introduction to Computer Science 1 What Actions Do We Have Part 2.
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,
Operator Overloading.
Chapter 18 - C++ Operator Overloading
Andy Wang Object Oriented Programming in C++ COP 3330
CSE1002 – Problem Solving with Object Oriented Programming
Overloading C++ supports the concept of overloading Two main types
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 argument’s value.
What Actions Do We Have Part 1
Chapter 1.2 Introduction to C++ Programming
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
Operator Overloading; String and Array Objects
Overloading Operator MySting Example
Computing Fundamentals
Object-Oriented Design (OOD) and C++
Polymorphism in C++ Operator Overloading
Chapter 2 Assignment and Interactive Input
Computer Programming FAST-NU FSB-CH Campus
Objectives Define polymorphism Overload functions
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
LEC Default Function Arguments, Ambiguity in Function Overloading and Operator Overloading.
C++ fundamentals Lecture 1, Chapter 2 – pp /22/2018 Y K Choi.
Operator Overloading; String and Array Objects
Operator Overloading.
Advanced Program Design with C++
Operator Overloading; String and Array Objects
Operator Overloading, Friends, and References
Operator Overloading.
Operator Overloading.
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
COP 3330 Object-oriented Programming in C++
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS31 Discussion 1D Winter18: week 6
Presentation transcript:

Chapter 6: UNDERSTANDING FRIENDS AND OVERLOADING OPERATORS

Outline Learn what a friend is Declare a friend function Examine the benefits of polymorphism and overloading Use a friend function to access data from two classes Learn the general rules that apply to operator overloading Overload an arithmetic operator Overload operators to work with an object and a primitive type Chain multiple mathematical operations in an expression Overload the insertion operator (<<) for output Overload the extraction operator (>>) for input Overload the prefix and postfix ++ and -- operators Overload the == operator Overload the = operator Overload the subscript and parenthesis operators

WHAT ARE FRIENDS? Encapsulation and data hiding are two primary features of object-oriented programs Sometimes, however, it is convenient to allow an outside, nonmember function to have access to a private data member. A friend function is a function that can access the non-public members of a class, even though the function itself is not a member of the class. A friend function is a normal function with special access privileges.

WHAT ARE FRIENDS? 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 C++ friend relationship is always one-sided. A class declaration must state which functions will be its friends; functions cannot declare that they are friends of a class.

WHAT ARE FRIENDS? friend functions can access private data, and the data members are private for a reason, friend functions should be used only when absolutely necessary

HOW TO DECLARE A FUNCTION AS A FRIEND

UNDERSTANDING THE BENEFITS OF OVERLOADING AND POLYMORPHISM interpret the meaning of “open” based on the context two functions the same name, but different parameter lists creating two or more constructors for the same class

USING A FRIEND FUNCTION TO ACCESS DATA FROM TWO CLASSES class Transaction { private: int transactionNum; int custNum; double amount; public: Transaction(int = 0, int = 0, double = 0.0); };

USING A FRIEND FUNCTION TO ACCESS DATA FROM TWO CLASSES » If you make both the balanceDue field in the Customer class and the amount field in the Transaction class public, then any function can use and modify them. However, this violates a basic principle of object-oriented programming. » If you create a payment application function that is not a member of either the Customer or the Transaction class, the function will not have access to the private data fields of either class. » If you make the payment application function a member of the Customer class, the function has access to balanceDue, but not to amount, which is private within the Transaction class.

USING A FRIEND FUNCTION TO ACCESS DATA FROM TWO CLASSES » If you make the payment application function a member of the Transaction class, the function has access to amount, but not to balanceDue, which is private within the Customer class. » If you create public get and set functions for both the Customer and Transaction classes, you can access and alter their private data fields in a controlled manner. This is the approach you almost always will want to take because it supports the object-oriented principles of data hiding and encapsulation. » If you alter both classes to make the payment application function a friend of them, the function can use data from each class.

USING A FRIEND FUNCTION TO ACCESS DATA FROM TWO CLASSES

USING A FORWARD DECLARATION The declaration of the applyTransaction()function is: friend void applyTransaction(Customer, Transaction);

#include<iostream> using namespace std; class Transaction; class Customer { friend void applyTransaction(Customer, Transaction); private: int custNum; double balanceDue; public: Customer(int = 0, double = 0.0); }; Customer::Customer(int num, double balance) custNum = num; balanceDue = balance; } class Transaction int transactionNum; double amount; Transaction(int = 0, int = 0, double = 0.0); Transaction::Transaction(int trans, int cust, double amt) { transactionNum = trans; custNum = cust; amount = amt; } void applyTransaction(Customer cust, Transaction trans) cout << "Customer #" << cust.custNum << " original balance of $" << cust.balanceDue << endl; cust.balanceDue += trans.amount; cout << "After transaction #" << trans.transactionNum << " for " << trans.amount << " the new balance is $" << int main() Transaction oneTrans(111, 888, -150.00); Customer oneCust(888, 200.00); applyTransaction(oneCust, oneTrans); return 0;

OVERLOADING OPERATORS—THE GENERAL RULES Operator overloading is the process by which you apply operators to your own abstract data types. The +, -, *, and / symbols make it easy to work with built-in data types such as int and double Unary operators that can be overloaded Binary operators Precedence of operators Operators that cannot be overloaded

Unary operators

Operators that cannot be overloaded

OVERLOADING AN ARITHMETIC OPERATOR #include<iostream> using namespace std; class Employee { private: int idNum; double salary; public: Employee(int, double); double addTwo(Employee); }; Employee::Employee(int id, double sal) idNum = id; salary = sal; } double Employee::addTwo(Employee emp) double total; total = salary + emp.salary; return total; int main() { Employee clerk(1234, 400.00); Employee driver(3456, 650.00); double sum; sum = clerk.addTwo(driver); cout << "Adding driver to clerk - Sum is $" << sum << endl; sum = driver.addTwo(clerk); cout << "Adding clerk to driver - Sum is $" << return 0; }

Employee class with an operator+() function #include<iostream> using namespace std; class Employee { private: int idNum; double salary; public: Employee(int, double); double operator+(Employee); }; Employee::Employee(int id, double sal) idNum = id; salary = sal; } double Employee::operator+(Employee emp) double total; total = salary + emp.salary; return total; int main() { Employee clerk(1234, 400.00); Employee driver(3456, 650.00); double sum; sum = clerk.operator+(driver); cout << "Using operator+() function - Sum is $" << sum << endl; sum = clerk + driver; cout << "Adding clerk to driver - Sum is $" << return 0; }

PAYING ATTENTION TO THE ORDER OF THE OPERANDS double Employee::operator-(Employee emp) { double difference; difference = salary - emp.salary; return difference; }

OVERLOADING AN OPERATOR TO WORK WITH AN OBJECT AND A PRIMITIVE TYPE Employee Employee::operator+(double raise) { Employee temp; temp.idNum = idNum; temp.salary = salary + raise; return temp; }

OVERLOADING OUTPUT ostream& operator<<(ostream&, int); ostream& operator<<(ostream&, double); ostream& operator<<(ostream&, float);

OVERLOADING THE PREFIX ++ AND – – OPERATORS

OVERLOADING THE == OPERATOR

OVERLOADING THE = OPERATOR #include<iostream> #include<string> using namespace std; class Classroom { private: string* student; int numStudents; int gradeLevel; public: Classroom(); ~Classroom(); void display(); Classroom& operator=(Classroom&); }; Classroom::Classroom() int x; cout << "What grade level is this class? "; cin >> gradeLevel; cout << "How many students in this class? "; cin >> numStudents; student = new string[numStudents]; for(x = 0; x < numStudents; ++x) cout << "Please enter the student's name "; cin >> student[x]; } Classroom::~Classroom() { delete [] student; } void Classroom::display() int x; cout << "Grade " << gradeLevel << " class list:" << endl; for(x = 0; x < numStudents; ++x) cout << student[x] << endl; Classroom& Classroom::operator=(Classroom& aClassroom) gradeLevel = aClassroom.gradeLevel; numStudents = aClassroom.numStudents; student = new string[numStudents]; for(x = 0; x < aClassroom.numStudents; ++x) student[x] = aClassroom.student[x]; return *this;

int main() { Classroom oneClass; Classroom anotherClass; cout << endl << "The original classroom before assignment:" <<endl; oneClass.display(); cout << endl << "The second classroom "; anotherClass.display(); oneClass = anotherClass; cout << endl << "The original classroom after assignment:" << endl; } cout << endl << "After the second class has gone out of scope:" <<endl; return 0;

OVERLOADING [ ] AND ( )

Summary Use a friend function to access data from two classes Operator overloading