Operators & Overloading Joe Meehean. Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in.

Slides:



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

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.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
All the Operators. Precedence An operator with higher precedence is done earlier (prededes) one with lower precedence –A higher precedence is indicated.
All the Operators. Precedence An operator with higher precedence is done earlier (prededes) one with lower precedence –A higher precedence is indicated.
1 9/20/06CS150 Introduction to Computer Science 1 Review: Exam 1.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading; String and Array Objects.
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 in C++
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
C++ Operators CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
Overloading Operators. Operators  Operators are functions, but with a different kind of name – a symbol.  Functions.
OperatorstMyn1 Operators The sequence in which different operators in an expression are executed is determined by the precedence of the operators. Operators.
CSC241 Object-Oriented Programming (OOP) Lecture No. 10.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
CS212: Object Oriented Analysis and Design Lecture 10: Copy constructor.
Basic Operators. What is an operator? using expression is equal to 9. Here, 4 and 5 are called operands and + is the operator Python language supports.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
Operator Overloading Operator Overloading allows a programmer to define new uses of the existing C/C++ operator symbols. –useful for defining common operations.
Computer Science Department CPS 235 Object Oriented Programming Paradigm Lecturer Aisha Khalid Khan Operator Overloading.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
CSC241 Object-Oriented Programming (OOP) Lecture No. 8.
Chapter 8 Operator Overloading, Friends, and References.
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.
Bit Operations Horton pp Why we need to work with bits Sometimes one bit is enough to store your data: say the gender of the student (e.g. 0.
15-Nov-15 All the Operators. operators.ppt 2 Precedence An operator with higher precedence is done earlier (precedes) one with lower precedence A higher.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
Slide 1 Chapter 8 Operator Overloading, Friends, and References.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
C# Operator Overloading and Type Conversions C#.NET Software Development Version 1.0.
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,
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.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 RAD due Friday in your Wiki. Presentations week 6 – next week. Schedule on next slide. Today: –Operator.
CS212: Object Oriented Analysis and Design Lecture 11: Operator Overloading-I.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 26 Clicker Questions December 3, 2009.
STRUCTURED PROGRAMMING C++ Operators. Content 2  C++ operators  Assignment operators  Arithmetic operators  Increment and decrement operators  Decision.
 Binary operators  Unary operators  Conversion Operators  Proxy Classes (simulating a reference) ▪ bitset example  Special operators  Indexing 
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
Rational Expressions relational operators logical operators order of precedence.
CS212: Object Oriented Analysis and Design Polymorphism (Using C++)
Operator Overloading.
Operator Overloading Introduction
Overloading C++ supports the concept of overloading Two main types
C++ Programming Language Lecture 4 C++ Basics – Part II
Operators and Expressions
Operators and Expressions
All the Operators 22-Nov-18.
Operator Overloading.
Operator Overloading; String and Array Objects
All the Operators 4-Dec-18.
Operator Overloading, Friends, and References
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,
COP 3330 Object-oriented Programming in C++
All the Operators 6-Apr-19.
All the Operators 13-Apr-19.
Operator Overloading; String and Array Objects
C++ Programming Language Lecture 4 C++ Basics – Part II
Presentation transcript:

Operators & Overloading Joe Meehean

Expressions Expression composed of operands combined with operators e.g., a + b Operands variables and literals in an expression e.g., a b Operators symbol that combine the operands e.g., + - / * % Result what is left after evaluating expression result of applying operators to operands 2

Expressions Operator types Unary takes only a single operand e.g., ! Binary takes two operands e.g., + * / % 3

Expressions How are expressions evaluated? Depends on associativity and precedence Precedence if expression contains more than 1 operator which operator to apply first operators with higher precedence applied first e.g., * 5 == 7 + (3 * 5) 4

Expressions How are expressions evaluated? Depends on associativity and precedence Associativity given multiple operators with the same precedence which operator to apply first depends on associativity Left associative apply operators from left to right e.g., == (2 + 3) + 5 Right associative apply operators from right to left e.g., == 2 + (3 + 5) 5

Arithmetic Operators 6 OperatorFunctionAssociativityLevel * +unary plusR1 − unary minusR1 *multiplicationL6 /divisionL6 %moduloL6 +additionL7 − subtractionL7 * lower level == higher precedence. Level 1 has highest precedence

Arithmetic Operators Dangers Illegal operations e.g., division by 0 causes program to crash Overflow value goes outside of legal range 2 byte signed short max value: ^15 (16 th bit reserved for sign) adding one pushes a 1 into the sign position causes value to go negative:

Relational & Logical Operators 8 OperatorFunctionAssociativityLevel * !logical notR3 <, <=less than (equal)L9 >, >=greater than (equal)L9 ==, !=(not) equalsL10 &&logical andL14 ||logical orL15 * lower level == higher precedence. Level 1 has highest precedence

Relational & Logical Operators Interesting info Relational operators do not chain, > e.g., a < b < c < d will not compile associativity is irrelevant 9

Relational & Logical Operators Interesting info Short-circuit evaluation given a series of conditions connected by || if any of the conditions is true, the expression is true conditions only evaluated until the first true condition is found e.g., a || b || c if a is true, b and c won’t be evaluated if a is false and b is true, only a and b will be evaluated 10

Relational & Logical Operators Interesting info Short-circuit evaluation given a series of conditions connected by && expression true only if all conditions are true conditions only evaluated until the first false condition is found e.g., a && b && c if a is false, b and c won’t be evaluated if a is true and b is false, only a and b will be evaluated power (avoid going out of bounds): while( i < theVector.size() && theVector[i] != 7){ i++; } 11

Bitwise Operators AND combines two bit sets bit in result only 1 if both bits in operands are 1 e.g., 0101 AND 1100 => 0100 OR combines two bit sets bit in result 1 if bit in either operand is 1 e.g., 0101 OR 1010 =>

Bitwise Operators NOT flips all of the bits e.g., 0101 => 1010 XOR combines two bit sets bit in results 1 only if exactly one bit in the operands was 1 e.g., 1010 XOR 1010 => 0000 e.g., 1110 XOR 1010 =>

Bitwise Operators left shift shifts all bits to the left e.g., 0011 => 0110 new bits are zero left-most bit falls off the end right shift shifts all bits to the right e.g., 0111 => 0011 new bits are zero right-most bit falls off the end 14

Bitwise Operators 15 OperatorFunctionAssociativityLevel * ~bitwise NOTR3 >left (right) shiftL8 &bitwise ANDL11 ^bitwise XORL12 |bitwise ORL13 * lower level == higher precedence. Level 1 has highest precedence

IO Operators bitwise shift operators overloaded for IO << insertion operator inserts data into output stream e.g., cout << a << endl; >> extraction operator extracts data from input stream e.g., cin >> a ; 16

Other Operators 17 OperatorFunctionAssociativityLevel * ()groupingL2 ++, --postfixL2 ++, --prefixR3 * Lower level == higher precedence. Level 1 has highest precedence

Assignment Operators 18 OperatorFunctionAssociativityLevel * =assignmentR17 +=, − =, *=, /=, %= arithmetic assignment R17 >>=, <<=, &=, |=, ^= bitwise assignmentR17 * Lower level == higher precedence. Level 1 has highest precedence

Assignment Operators Assignment operator has low precedence and is right associative very important Right associativity allows: a = b = c = 0 Low precedence a = b + c => a = (b + c) makes logical sense 19

Questions? 20

Operator Overloading Redefine operators for classes we write Lets us make intuitive use of operators like [] for vector and string += for string append Powerful and easy to read v[i] vs. v.get(i) str += “Hello” vs. str.append(“Hello”) 21

Operator Overloading 2 different types of operator overloading Member overloading defined as a member method of a class first operand is always this if binary operator, method takes 1 parameter the other operand if unary operator, method takes 0 parameters generally best choice for assignment/modifier operators = +=, -=, … [] -> 22

Operator Overloading 2 different types of operator overloading Nonmember overloading defined as a global function if binary operator, method takes 2 parameter if unary operator, method takes 1 parameters generally best choice for symmetric operators arithmetic equality relational bitwise 23

Operator Overloading Syntax: member method requires the operator keyword type Class::operator +=(type) e.g., bool UsedBook::operator ==(const UsedBook& rhs) Syntax: nonmember method type1 operator +=(type, type) e.g., bool operator==(const UsedBook& lhs, const UsedBook& rhs) 24

Operator Overloading Limitations can overload all operators discussed in class except: ::,.*,., ?: cannot invent new operators: operator ** at least one operand must be a class precedence and associativity cannot be changed Short-circuit evaluations is not preserved &&, || both operands are always evaluate evaluation order is not guaranteed 25

Operator Overloading Operators you should define if it makes sense For use with STL < == != : to go along with == To print your class << 26

Operator Overloading Overloading the output operator << Non-member method 1st parameter is always a reference to an ostream cout is an instance of the ostream class reference because ostream cannot be copied 2 nd parameter is often const reference to class object printing an object rarely changes it reference prevents making unnecessary copies Always returns an ostream reference so we can chain << operators together e.g., cout << a << b << c << endl Do not add an end line when writing operator << 27

Operator Overloading 28 ostream& operator<<(ostream& os, const Book& book){ os << book.author_ << “ “; os << book.title_ << “ “; os << book.retail_price_; }

Operator Overloading Non-member function in previous example had access to Book’s private member data. How? Friends class can call other classes or method friends friends can access private member data and methods Syntax: friend classes friend class class1 e.g., friend class Song 29

Operator Overloading Non-member function in previous example had access to Book’s private member data. How? Friends class can call other classes or method friends friends can access private member data and methods Syntax: friend methods friend return_type name(type1 var1, type2 var2,…) e.g., friend ostream& operator<<(ostream& os, const Book& b); does not declare this method just says this method exists and is a friend 30

Operator Overloading 31 class Song{ private: string title_; string duration_s; string artist_; public: Song(...);... // this is not declaring this method // this method is not a member method of Song friend ostream& operator<<(ostream& os, const Song& s); };

Questions? 32