lecture29 Operator Overloading

# lecture29 Operator Overloading - 1 Janice Regan, CMPT 128,...

This preview shows pages 1–6. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1 Janice Regan, CMPT 128, February. 2007 CMPT 128: Introduction to Computing Science for Engineering Students Operator Overloading Janice Regan, CMPT 128, February 2007 2 Learning Objectives Basic Operator Overloading Unary operators As member functions References and More Overloading << and >> Operators: = , , ++, -- Janice Regan, CMPT 128, February 2007 3 Operator Overloading Introduction You can think of an operator as a special function that is called in a different way (alternate syntax) from ordinary functions Operators *, /, +, -, %, ==, << etc. For example to call special function * If we think of the call to the function as *(5,q) Think of the function name as * 5,q are the arguments Function * returns product of its arguments We have special syntax for the very commonly used functions to implement operators *(5,q) is actually written 5*q within your code However, this is still executing code that looks similar to a function Janice Regan, CMPT 128, February 2007 4 Operator Overloading Perspective Built-in operators e.g. *,/,+, -, = , %, ==, !=, << , > Appropriate subset of operators work with each built in C++ type Implementation syntax: operator operand operator Now we are defining new types (classes). How do we make the operators work on the objects in our classes OVERLOADING!! Want to use the same syntax as for built in types when we use the operators we are used to using for built in types How do we define our functions to accomplish this? Remember always overload only functions which perform similar actions! Janice Regan, CMPT 128, February 2007 5 Overloading Basics To indicate the name of the operator to be overloaded the keyword operator followed by the operator itself replace the identifier for a typical function Formal parameters of the function are const, so that they cannot be modified by the operator (const is not required) Example Declaration: const Money operator +( const Money& amount1, const Money& amount2); Overloads + for operands of type Money Janice Regan, CMPT 128, February 2007...
View Full Document

## This note was uploaded on 05/18/2010 for the course CMPT 128 taught by Professor Regan during the Spring '08 term at Simon Fraser.

### Page1 / 22

lecture29 Operator Overloading - 1 Janice Regan, CMPT 128,...

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online