Lecture 4 OOP Course. 4. Operators Using constructors: String int main(){ String s1(“My String”); String s2(s1); String s3; s3=s1; } int main(){ String.

Slides:



Advertisements
Similar presentations
Operator overloading redefine the operations of operators
Advertisements

Class and Objects.
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
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
OOP Spring 2007 – Recitation 31 Object Oriented Programming Spring 2007 Recitation 3.
Chapter 13: Overloading.
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator Overloading CS 308 – Data Structures What is operator overloading? Changing the definition of an operator so it can be applied on the objects.
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++
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
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:
Object Oriented Programming in C++ Chapter5 Operator Overloading.
Overloading Operators. Operators  Operators are functions, but with a different kind of name – a symbol.  Functions.
CSC241 Object-Oriented Programming (OOP) Lecture No. 10.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Operator Overloading ~ and User Defined Conversions.
CSCI 383 Object-Oriented Programming & Design Lecture 13 Martin van Bommel.
Case Study - Fractions Timothy Budd Oregon State University.
Operator Overloading Like most languages, C++ supports a set of operators for its built-in types. Example: int x=2+3; // x=5 However, most concepts for.
J. P. Cohoon and J. W. Davidson © 1997 McGraw-Hill, Inc. Templates Generic functions and classes.
Copyright  Hannu Laine C++-programming Part 4: Operator overloading.
Operator Overloading Operator Overloading allows a programmer to define new uses of the existing C/C++ operator symbols. –useful for defining common operations.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAM DESIGN WITH C++ Part 9:
CSC241 Object-Oriented Programming (OOP) Lecture No. 8.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
LECTURE LECTURE 13 Operator Overloading Textbook p.203—216 Today: const member functions Overloading Operators Postfix/infix increment.
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,
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;
Operator Overloading. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
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 Lecture 17 Operator Overloading. 2 Introduction A number of predefined operators can be applied to the built- in standard types. These operators can.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 RAD due Friday in your Wiki. Presentations week 6 – next week. Schedule on next slide. Today: –Operator.
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.
Operator Overloading Moshe Fresko Bar-Ilan University Object Oriented Programing
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.
Previous lecture Introduction to OOP and C++ Data Abstraction –String example.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 14: More About Classes.
 Binary operators  Unary operators  Conversion Operators  Proxy Classes (simulating a reference) ▪ bitset example  Special operators  Indexing 
Object Oriented Programming COP3330 / CGS5409.  Arithmetic Operator Overloading  Increment (++) / Decrement (--)  In-class exercise.
Operator Overloading.
CSE1002 – Problem Solving with Object Oriented Programming
Operator Overloading CS 3370 – C++ Chapter 14.
Yan Shi CS/SE 2630 Lecture Notes
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.
Chapter 14: More About Classes.
Overloading Operator MySting Example
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
Jim Fawcett Copyright ©
Operator Overloading CSCE 121 J. Michael Moore
Operator Overloading.
Advanced Program Design with C++
תכנות מכוון עצמים ו- C++ יחידה 06 העמסת אופרטורים
Operator Overloading.
CISC/CMPE320 - Prof. McLeod
COP 3330 Object-oriented Programming in C++
Operator Overloading I
Operator Overloading CSCE 121 Based on Slides created by Carlos Soto.
Jim Fawcett Copyright ©
Presentation transcript:

Lecture 4 OOP Course

4. Operators

Using constructors: String int main(){ String s1(“My String”); String s2(s1); String s3; s3=s1; } int main(){ String s1(“My String”); String s2(s1); String s3=s1; } What’s the difference?

Operators Definition We want User-defined types to behave the same way as built-in types We want operators to be supported, for the uniform convention The language allows this And the usage: class String { char* chars; int length; public: String(); String(char* value); ~String(); String& operator=(const String& s); bool operator>(const String& s); String& operator+=(const String& s); char* getString(); void setString(char* value); };

Operators - Usage Who is the caller? Who is the parameter? void main() { String s1 =“OOP ”; String s2 =“Course”; s1 += s2; } Invokes “function” s1.operator+=(s2)‏

Operators - Implementation bool String::operator>(const string& s) { return strcmp(m_str, s.m_str) > 0; }

Operators - Implementation String &String::operator+=(const String &s){ int new_len = length + s.length + 1; char *v = new char [new_len]; strcpy(v, chars); strcat(v, s.chars); delete[] chars; chars = v; length = new_len; return *this; } Within a member function: explicit name for the object on which the function is called

Operators – Implementation (first version)‏ String String::operator+(const String &s){ String tmp = *this; tmp += s; return tmp; }

Operators: Good news Can be defined and re-defined =Defined by default: = Rules: –At least one operand must be class –Cannot define new operators –Cannot change precedence/associativity

operators overloading - what can we overload? + - * / % ^ & | ! = +=-=*=/=%= ^=&=|= > >=== != =&&||++--, ->*->()[] what not ?..* :: ? : sizeof

Example: Class Vector class Vector2D{ private: double x, y; public: Vector2D(double x_init=0, double y_init=0): x(x_init), y(y_init){} double getX() const {return x;} double getY() const {return y;} Vector2D add(const Vector2D& other) const {return Vector2D(x+other.x, y+other.y);} } //usage: Vector2D a(3,2), b(1); Vector2D c = a.add(b); cout << “(“ << c.getX() << “,” << c.getY() << ‘)’;

Example: Class Vector class Vector2D{ private: double x, y; public: Vector2D(double x_init=0, double y_init=0): x(x_init), y(y_init){} double getX() const {return x;} double getY() const {return y;} Vector2D operator+(const Vector2D& other) const {return Vector2D(x+other.x, y+other.y);} {return Vector2D(x+other.x, y+other.y);} } //usage: Vector2D a(3,2), b(1); Vector2D c = a+b; cout << “(“ << c.getX() << “,” << c.getY() << ‘)’;

Overloading ++ and -- Pre- and post-increment –x = 0; cout << x++; cout <<++x; Pre-increment and pre-decrement – –Vector2D operator++(); Post-increment and post-decrement – use dummy parameter –Vector2D operator++(int);

Friend access modifier The following will work: –c=a+b –c=a+1; The following will not work: –c=1+b The first argument cannot be built-in! Solution: define the operator not as a member function –But what about encapsulation? friend :Access modifier friend : allows to access private fields and methods of the class

Example: Class Vector class Vector2D{ private: double x, y; public: Vector2D(double x_init=0, double y_init=0): x(x_init), y(y_init){} double getX() const {return x;} double getY() const {return y;} friend Vector2D operator+( const Vector2D& left, const Vector2D& right); } Vector2D operator+(const Vector2D& left, const Vector2D& right){ return Vector2D(left.x+right.x, left.y+right.y);} //usage: Vector2D a(3,2), b(1); Vector2D c = a+b; cout << “(“ << c.getX() << “,” << c.getY() << ‘)’;

Class Vector: more operators class Vector2D{... Vector2D operator-() const{return Vector2D(-x, -y);} double operator[](int index) const {return (index == 0)?x:y;} friend ostream& operator<<( ostream& ostr, const Vector2D& v); } ostream& operator<<(ostream& ostr, const Vector2D& v){ return ostr << “(“ << v.x << “,” << v.y << ‘)’; } //usage: Vector2D a(3,2), b(1); Vector2D c = -a; cout << “(“ << c[0] << “,” << c[1] << ‘)’; cout << c << b << a;

Member vs. non-member operators Use membersUse members –When returning a reference operators =, [] –Unary operators, usually –Asymmetric operators, whenever possible Use friends forUse friends for –Symmetric operators –Operators on classes which cannot be altered istream, ostreamh

5 Operator=

operator= By default: bitwise copy Vector2D –Will this work for Vector2D? String –Will this work for String? Rule of thumb: either you need all of {destructor, copy-constructor, operator=} or you need none Rules: MyClass& MyClass::operator=(const MyClass& other)‏ *this –Return *this –Define as member to ensure target object is assignable

operator= : example class String{... public: String& operator=(const String& other){ if (this == &other) return *this; if (chars != NULL) delete[] chars; length = other.length; chars = new char[length+1]; strcpy(chars, other.chars); return *this; }

Operator examples

The Rational Number Class class Rational { public: Rational(int top = 0, int bottom = 1}: t(top), b(bottom) { normalize();} //... private: int t,b; void normalize() // A private member function {if(b<0) { b = -b; t = -t; } int divisor = gcd(abs(t),b); t /= divisor; b /= divesor; } }; gcd defined elsewhere

A Unary Operator Member class Rational { //... public: //... Rational operator-() const { return Rational(-t,b);} //... }; int main()‏ { Rational r(-1,3); Rational s = -r; // Activates r.operator-()‏.... }

Arithmetic Operator Members class Rational { //... public: //... Rational& operator+=(const Rational& r) const{ t = t*r.b+r.t*b; b = b*r.b; normalize(); return *this; } Rational& operator-=(const Rational& r) const{ t = t*r.b-r.t*b; b = b*r.b; normalize(); return *this; } };

Arithmetic Operator Members class Rational { //... public: //... Rational& operator*=(const Rational& r) const{ t = t*r.t; b = b*r.b; normalize(); return *this; } Rational& operator/=(const Rational& r) const{ t = t*r.b; b = b*r.t); normalize(); return *this; } };

Symmetric Operators class Rational { //... public: //... }; Rational operator+(const Rational& r1, const Rational& r2){...} Rational operator-(const Rational& r1, const Rational& r2){...} Rational operator*(const Rational& r1, const Rational& r2)‏ { Rational tmp(r1); return tmp*=r2; } friend Rational operator/(const Rational& r1, const Rational& r2){...}

Friends Operators class Rational { //... public: //... friend bool operator==(const Rational&, const Rational&); friend bool operator!=(const Rational&, const Rational&); friend bool operator<=(const Rational&, const Rational&); friend bool operator>=(const Rational&, const Rational&); friend bool operator<(const Rational&, const Rational&); friend bool operator>(const Rational&, const Rational&); }; Not all of them need to be friend

Adding I/O to the Rational Class class Rational { public: //... friend istream& operator>>(istream& in, Rational& r); friend ostream& operator<<(ostream& out, Rational& r); }; istream& operator>>(istream& in, Rational& r){ in >> r.t >> r.b; return in; } ostream& operator<<(ostream& out, Rational& r){ out << r.t << '\' << r.b; return out; }

Using I/O in the Rational Class int main()‏ { Rational r1(1,6), r2(1,3); cout << r1 << '+' << r2 << '=' << r1+r2 << endl; // will print: 1/6 + 1/3 = 1/2 return 0; }