Operator overloading and friend functions

# Operator overloading and friend functions - Lecture 4...

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

Lecture 4 Operator Overloading & Friend Functions

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

View Full Document
Outline We already covered function overloading Overloaded functions Overloading functions with default parameters Operator Overloading Operator functions Overloading arithmetic and comparison operators Overloading input and output operators Overloading assignment, increment and decrement operators Overloading subscript and function call operators Friend functions Case studies
Review of Function Overloading C++ allows more than one definition for the same function name for convenience Example void print (); void print (Time t); void print (Employee & e); Void print (Employee e); //can we overload here? void print (double a[], int size); void print (const double a[], int size); //any problem here?

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

View Full Document
Function with Default Parameter Example 1 void print(double d[], int size = 10); double a[MAX]; print (a, MAX); print (a); Example 2 class Point {Point(double xx=0, double yy=0); … }; Point p1(3.4, 5.5), p_x(5.0), origin; //Note 1: default value may not show in implementations Point::Point(double xx, double yy) {x=xx; y=yy; } //Note 2: in this case you cannot have x take default value while y has an actual parameter
Operator Functions Use operator symbol as function name Overloading the existing operators Must have at least one parameter of class type or enumerated type Example enum Days {SUN, MON, TUE, WED, THU, FRI, SAT}; Days operator+ (const Days& a, int d); int operator- (const Days& a, const Days &b); Days today = WED, weekend = SUN; int difference = today – weekend; Days tomorrow = today + 1;

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

View Full Document
Operator Function vs. Regular Function Mainly differs in the usage Use of regular function int subtract (const Days &a, const Days &b); Days today, weekend; int difference = subtract (today, weekend); Use of operator function
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 23

Operator overloading and friend functions - Lecture 4...

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

View Full Document
Ask a homework question - tutors are online