Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.

Slides:



Advertisements
Similar presentations
Chapter 11 Operator Overloading; String and Array Objects Chapter 11 Operator Overloading; String and Array Objects Part I.
Advertisements

Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
Introduction to Programming Lecture 39. Copy Constructor.
Operator Overloading Fundamentals
Class and Objects.
Operator Overloading. Basics Define operations on user-defined data types –Perform same operation as it is supposed to but, with operands of the user-defined.
Rossella Lau Lecture 10, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 10: Operator overload  Operator overload.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 18 - C++ Operator Overloading Outline 18.1Introduction.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 18 - Operator Overloading Outline 18.1Introduction 18.2Fundamentals of Operator Overloading 18.3Restrictions.
Chapter 13: Overloading.
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.
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator Overloading 1. Introduction Let’s define a class for Complex numbers: class Complex { private: double real, image; public: Complex () : real(0.0),
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Operator overloading Object Oriented Programming.
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 14: Overloading and Templates.
Chapter 18 - Operator Overloading Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
More About Classes Chapter Instance And Static Members instance variable: a member variable in a class. Each object has its own copy. static variable:
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 15: Overloading and Templates.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
CSCI 383 Object-Oriented Programming & Design Lecture 13 Martin van Bommel.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
CS212: Object Oriented Analysis and Design Lecture 10: Copy constructor.
Case Study - Fractions Timothy Budd Oregon State University.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
Chapter 14 More About Classes. Chapter 13 slide 2 Topics 13.1 Instance and Static Members 13.2 Friends of Classes 13.3 Memberwise Assignment 13.4 Copy.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
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 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 5 1.
AL-HUSEEN BIN TALAL UNIVERSITY College of Engineering Department of Computer Engineering Object-Oriented Programming Course No.: Fall 2014 Overloading.
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 14: More About Classes.
1 CSC241: Object Oriented Programming Lecture No 08.
Dale Roberts Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer and Information Science,
Operator Overloading.
Chapter 18 - C++ Operator Overloading
Yan Shi CS/SE 2630 Lecture Notes
Overloading C++ supports the concept of overloading Two main types
Overloading Operator MySting Example
14.4 Copy Constructors.
Chapter 15: Overloading and Templates
Operator Overloading.
Operator Overloading; String and Array Objects
Operator Overloading.
CISC/CMPE320 - Prof. McLeod
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
Operator overloading Friend Function This Operator Inline Function
Presentation transcript:

Overloading Operator MySting Example

Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient but may make program difficult to understand

Operator Overloading Function can be overloaded Operators can also be overloaded as ordinary functions, – overload built-in C++ operators: give different meaning to operators such as +, +=, <<, etc. – taking one or more arguments of class or reference – Keyword operator To use an operator on a class object it must be overloaded except the assignment operator (=) or the address operator (&) – Assignment operator by default performs member_wise assignment – Address operator (&) by default returns the address of an object

Overloading an operator Write function definition as normal Function name is keyword operator followed by the symbol for the operator being overloaded operator+ used to overload the addition operator ( + ) add function + operator

Prototype class foo{ public : foo operator--(); // overload unary minus foo operator-(int); //binary minus foo-int foo operator-(foo); // foo - foo }; foo operator-(int, foo) ; // int - foo foo operator-(int, foo*) ; // illegal need foo or foo&

Member vs non-member functions Operator functions can be member or non- member functions – When overloading ( ), [ ], -> or any of the assignment operators, must use a member function Operator functions as member functions – implicitly acting on this object – Leftmost operand must be an object (or reference to an object) of the class – If left operand of a different type, operator function must be a non-member function

Non-member Function Operator functions as non-member functions – Must be friend s if needs to access private or protected members – Enable the operator to be commutative

Overloading restrictions Can not create new operators The precedence, associativity and arity do not change can not overload operators for built-in types – Cannot change how two integers are added

MyString Design MyString class: – Represent a sequence of characters – the length of the string is important – data member: s : pointer len – methods: constructor: int n or char * length, print, destructor

Declare the Class my_string class MyString{ public: MyString(int n); MyString(const char * str); ~ MyString(); int length() const ; //const member function void print() const; private: char * s; int len; };

Constructors MyString :: MyString(int n) { s = new char[n+1]; s[0] = ‘\0'; len =n; } MyString :: MyString(const char * str) { len = strlen(str); s = new char[len+1]; strcpy(s,str); }

Overload Operator + (MyString) member function Prototype: MyString operator +(const MyString &b) const; Definition: MyString MyString ::operator+ ( const MyString &b) const {cout << "member +" << endl; char * temp = new char[this->len + b.len +1]; strcpy(temp, this->s); strcat(temp, b.s); MyString str(temp); return str; }

Returning Local Object from a function Returning an object invokes the copy constructor while returning a reference doesn't. If a method or function returns a local object, it should return an object, not a reference. It is an error to return a pointer to a local object. Once the function completes, the local object are freed. The pointer would be a dangling pointer that refers to a nonexistent object.

Overload Operator + non-member function friend MyString operator+(const MyString & a, const MyString &b); MyString operator+(const MyString &a, const MyString &b) {cout<< "nonmember +" << endl; char * temp = new char[a.len + b.len + 1]; strcpy(temp, a.s); strcat(temp, b.s); MyString ss(temp); return ss; }

Overloading the Assignment Operator copy constructors copy constructors Called when a new object is created and set equal to an existing instance Called when a new object is created and set equal to an existing instance What’s the difference between the following lines of code? What’s the difference between the following lines of code? MyString str1,str2; … // What’s the difference between the following two // lines of code? MyString aString = str1; str2 = str1; The first assignment involves a copy constructor since a new object is being created. The first assignment involves a copy constructor since a new object is being created. The second is straight assignment to an existing variable, so no copy constructor is involved. The second is straight assignment to an existing variable, so no copy constructor is involved.

Overloading the Assignment Operator (cont) Remember, C++ will define a default and naïve copy constructor for you if you don’t provide one. Remember, C++ will define a default and naïve copy constructor for you if you don’t provide one. It will just copy member variables (potential for dangling pointers) It will just copy member variables (potential for dangling pointers) In the case of MyString, we’d need to override the default copy constructor to make sure the storage was copied properly. In the case of MyString, we’d need to override the default copy constructor to make sure the storage was copied properly. MyString::MyString(MyString &aCopy) { // Copy storage into new instance if necessary... } Again, this will take care of the case where someone tries to assign to a MyString variable when it is declared : Again, this will take care of the case where someone tries to assign to a MyString variable when it is declared : MyString aStr = anotherStr; MyString aStr = anotherStr;

Overloading the Assignment Operator (cont) However, when we need to handle the case where an existing variable is assigned a new value via the assignment operator, we overload the assignment operator: However, when we need to handle the case where an existing variable is assigned a new value via the assignment operator, we overload the assignment operator: The = operator is another special case binary operator... The = operator is another special case binary operator... MyString &MyString::operator=(const MyString &sourceStr) { //set the value return *this; // Huh? return *this; // Huh?} Remember that when overloading the = operator you are going to be assigning to an existing instance. If that instance has dynamically allocated data it should be freed. Remember that when overloading the = operator you are going to be assigning to an existing instance. If that instance has dynamically allocated data it should be freed. We return a reference so that str1 = str2 = str3 works... We return a reference so that str1 = str2 = str3 works...

Overloading the Assignment Operator (cont) we should always make sure that our source and destinations aren’t the same.. we should always make sure that our source and destinations aren’t the same.. We do this by adding the following code: We do this by adding the following code: MyString & MyString::operator=(const MyString &sourceStr) { // Make sure we actually have two pointers if (this != &sourceStr) if (this != &sourceStr) //set the value //set the value return *this; return *this;} “ this ”, “ this ”, is a pointer to the current instance of the class we are in. is a pointer to the current instance of the class we are in.

Overload = (MyString) MyString & MyString ::operator =(const MyString & str) { if (this != &str) //important, avoid self-assignment { len = str.len; delete [] s; s = new char [len]; strcpy(s, str.s); } return *this; }

Overload += (MyString) // += operator MyString &MyString ::operator+=(const MyString &str) { this->len += str.len + len ; char *tempPtr = new char[len +1]; strcpy(tempPtr, s); strcat(tempPtr, str.s); delete []s; s= tempPtr; return *this; }

Overload Subscripting char & my_string::operator [](int i) { return this->s[i]; } my_string ms1(“hello”); ms1[0] = '!'; // subscript operator [], returning reference

Friend Functions The keyword friend is function specifier It gives nonmember function access to the hidden members of the class escaping the data hiding restriction Make sure you have a good reason for escaping the restriction

Declare friend functions Declare in the class to which the function is a friend Good: put in the public part of the class Member functions of one class can be friend of another class, use the class scope quantifier All member functions of one class are friend functions of another, just write friend class classname

Overloading I/O Operator << The operator << has two arguments – ostream & – the ADT It must produce an ostream & Use a reference since you don’t want to copy the stream object

Overload << (my_string) friend ostream & operator<<(ostream &, const my_string &); ostream& operator<<(ostream &out, const my_string &str) { return (out << str.s << endl); }

>> istream& operator >> (istream &out, my_string &str)