Overloading Operator MySting Example

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.
 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.
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,
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.
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:
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
CSCI 383 Object-Oriented Programming & Design Lecture 13 Martin van Bommel.
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.
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.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
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.
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.
1 CS161 Introduction to Computer Science Topic #16.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
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 Ugly Realities The Dark Side of C++ Chapter 12.
Operator Overloading.
Chapter 18 - C++ Operator Overloading
Yan Shi CS/SE 2630 Lecture Notes
Overloading C++ supports the concept of overloading Two main types
Procedural and Object-Oriented Programming
Pointers and Dynamic Arrays
Learning Objectives Pointers as dada members
Chapter 13: Overloading and Templates
Chapter 14: More About Classes.
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
Operator Overloading; String and Array Objects
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Constructor & Destructor
14.4 Copy Constructors.
Chapter 15: Overloading and Templates
The dirty secrets of objects
Chapter 14: More About Classes.
Introduction to Classes
Operator Overloading; String and Array Objects
Operator Overloading.
Operator Overloading; String and Array Objects
Operator overloading Dr. Bhargavi Goswami
Operator Overloading.
CISC/CMPE320 - Prof. McLeod
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
9-10 Classes: A Deeper Look.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
CS410 – Software Engineering Lecture #5: C++ Basics III
COP 3330 Object-oriented Programming in C++
Chapter 18 - Operator Overloading
C++ Class Members Class Definition class Name { public: constructor(s)
Operator overloading Friend Function This Operator Inline Function
9-10 Classes: A Deeper Look.
SPL – PS3 C++ Classes.
Presentation transcript:

Overloading Operator MySting Example

Operator Overloading 1+2 Matrix M1 + M2 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

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 friends 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 Called when a new object is created and set equal to an existing instance 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 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. 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. 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: 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: The = operator is another special case binary operator... MyString &MyString::operator=(const MyString &sourceStr) { //set the value 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. 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 do this by adding the following code: MyString & MyString::operator=(const MyString &sourceStr) { // Make sure we actually have two pointers if (this != &sourceStr) //set the value return *this; } “this”, 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)