Operator overloading and friend functions

Operator overloading and friend functions - Lecture 4...

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

View Full Document Right Arrow Icon
Lecture 4 Operator Overloading & Friend Functions
Background image of page 1

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

View Full DocumentRight Arrow Icon
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
Background image of page 2
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?
Background image of page 3

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

View Full DocumentRight Arrow Icon
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
Background image of page 4
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;
Background image of page 5

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

View Full DocumentRight Arrow Icon
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
Background image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

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 Right Arrow Icon
Ask a homework question - tutors are online