11/17/2008MET CS 563 - Fall 2008 8.Overloading Functions and Operators 1 8. Overloading Operators...

39
11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators 1 8. Overloading Operators 8. Overloading Operators Main Idea: Main Idea: Use the same function name (function overload) or operator symbol (operator overload) to perform different computations, initializations or other actions.
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    219
  • download

    0

Transcript of 11/17/2008MET CS 563 - Fall 2008 8.Overloading Functions and Operators 1 8. Overloading Operators...

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

1

8. Overloading Operators8. Overloading Operators

Main Idea: Main Idea: Use the same function name (function overload) or operator symbol (operator overload) to perform different computations, initializations or other actions.

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

2

Example 2: Overloading the class constructorAssume a complex class type has been definedclass Complex {…};We want to be able to initialize a class object in different ways, e.g. by giving values to its data members or by initializing it to some object of the same class Solution: overload the class constructor, so that

Complex first(re, im);and

Complex second(first);

can be used.

Overload: Examples

argument values of the type of the corresponding data members

single argument of type Complex, the same type as the object being initialized

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

3

Example 3: We want to manipulate user defined objects, such as Date class objects or aggregate types such as strings the same way as we manipulate integers or floats, e.g.

a) Overloading the '<' operator for Date today < tomorrow should produce true

b) the '+' and '==' operator for strings

"Welcome " + " home !" should produce "Welcome home !" "myPassword" == "myPasswd" should produce false

Overload: Examples (continued)

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

4

Overloading OperatorsOverloading OperatorsGoal:Goal: Manipulate aggregate data types, such as arrays, structures, classes in the same manner as built-in types, i.e. with infix operators that perform user defined operations on the objects.

Main Idea:Main Idea: A binary operator is a function with two arguments, e.g. the expression

3+5 that evaluates to 8 is the same as the function plus()

plus(3, 5) returning the value 8. Thus operator overload is in essence function overload. In order to implement it we need to write the appropriate definitions and to agree on a way to unambiguously relate these definitions to the operator symbol.

Example:Example: operator + {…},

operator - {…}

Syntax:Syntax: operator <OperatorSymbol> {…}

keyword

overloaded operator

function body

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

5

Implementing Operator Overload: Implementing Operator Overload: Member Function or Member Function or friendfriend Function ? Function ?

A fundamental question of implementing operator overload is:

Can we always implement it as a member function of the class Can we always implement it as a member function of the class or do we need another mechanism as well? or do we need another mechanism as well?

We will explore this question by overloading the '+' operator for a user defined class type Rational for rational numbers. The class Rational represents the rational numbers, i.e. all numbers that can be represented as

p/ q where p and q are integers, e.g 2/3, 1/4, etc.The class includes the arithmetic and comparison operators and prints the rational number in quotient form by keeping the nominator and denominator as small as possible (as shown in the above examples).

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

6

Class Class RationalRational

RationalInterface / Behavior

Initialize itself to 0

Perform addition '+' with integers and rationals//other arithmetic operations…

Perform comparison '<' with integers and rationals//other comparison operations…

Tell its value in reduced quotient form

Attributes / Data and Internalsnominatordenominatorreducing the nominator and denominator to smallest value

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

7

(i) First Try: Overloaded (i) First Try: Overloaded '+''+' as a Member Function of class Rational as a Member Function of class Rational

class Rational{public:

Rational(int n=0, int d=1); //constructor initializing to 0 (0/1)//overloaded '+' prototype//input: single argument of type Rational,//returns value of (input + object)Rational operator+(const Rational& ); …

private:int nom; //nominatorint denom; //denominator… //functions for reducing nom and denom to smallest values

};

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

8

Class Class RationalRational - Constructors and Use of Overloaded '+' - Constructors and Use of Overloaded '+'

Constructor Definition:Constructor Definition:Rational :: Rational (int n, int d): nom(n), denom(d) {} Object Definitions: Object Definitions:

Rational t(5,4), s(3), u, v;

Use of Overloaded Operator:Use of Overloaded Operator:

Function Style (acc. Signature): t.operator+(s);

Operator Style (Shorthand): t + s;

function name according to syntax

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

9

Class Class RationalRational - Definition of Overloaded '+' as Member Function - Definition of Overloaded '+' as Member Function

Rational Rational :: operator+(const Rational &b ) { Rational sum; sum.nom = b.denom * nom + b.nom * denom; sum.denom = denom * b.denom; sum.reduce();

return sum;}

Similar definitions can be written for the remaining binary arithmetic operators such as -, *, /, etc.

Use:Use: t.operator+(s);t + s; t + 5; //works as 5 becomes the initial value for argument b5 + t; // illegal!!! 5 is a literal and 5.operator is not defined!!

Problem: t+5 5+t !! when using our new + operatorThe addition is not commutative contrary to everything we have been taught since elementary school. Not a good idea.

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

10

Class Class RationalRational - Declaring Overloaded '+' as - Declaring Overloaded '+' as friendfriend Function within the class Function within the class

class Rational {public:

Rational(int n=0, int d=1); //constructor

friend Rational operator+( const Rational&, const Rational&);//overloaded '+' prototype as friend function//input two arguments of type Rational,//returns sum of two arguments…//Similar declarations can be written for the remaining binary

//arithmetic operators such as -, *, /, etc.…

private: //same as in previous definitionint nom; //nominatorint denom; //denominator//functions for reducing nom and denom to smallest values

};

keyword argument1

argument2

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

11

Defining theDefining the Overloaded '+' Overloaded '+' friendfriend Function Outside the Class Function Outside the Class

Rational operator+( const Rational &a, const Rational &b ) { Rational sum; sum.nom = b.denom * a.nom + b.nom * a.denom; sum.denom = a.denom * b.denom; sum.reduce(); return sum;}

Similar definitions can be written for the remaining binary arithmetic operators such as -, *, /, etc.

Note: The definition has no indication that there is any relation to some class(es). It is a regular function definition and only the class can give it special meaning by declaring it a friend and giving access to its private data members.

Use:Use: operator+(t, s);t + s; t + 5; //works as 5 becomes the initial value for argument b5 + t; // works as well!!! 5 is a literal for argument a!!

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

12

(iii) Overloaded Computer Specific Operators Return Objects Not Just Values (iii) Overloaded Computer Specific Operators Return Objects Not Just Values

Important Shared Characteristics:Important Shared Characteristics: I/O as well as assignment operators should return objects, not just values to allow compound statements, such as

cout << "The sum is " << a+b; t += s += a;

Assignment I/OObject of output stream class ostream

modified coutof type ostream resulting from insertion of "The sum is " in cout

s = s +a;returns object s

modified coutof type ostream resulting from insertion of a+b in previously modified cout

left-to-right associativity

t = t +s;returns object t

right -to- left associativity

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

13

Overloaded Computer Specific Operators: I/O Friends and Assignment MembersOverloaded Computer Specific Operators: I/O Friends and Assignment Members

Input / Output Input / Output OperatorsOperatorsare implemented as are implemented as

friendfriend functions:functions:

Important Difference:Important Difference:

cout << a+b; t += s;

Assignment I/O

lhs and rhs are of different types

lhs and rhs are of the same type

Assignment Assignment Operators Operatorsare implemented as are implemented as

membermember functions:functions:

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

14

Another look at class Rationalclass Rational {public:

Rational (int = 0, int = 1 ); // default constructor//Arithmetic operators as friend functions

friend Rational operator+( const Rational&, const Rational& );//Similarly the remaining arithmetic operators

//Comparison operators as friend functions friend bool operator>( const Rational&, const Rational& );

//Similarly the remaining comparison operators //Output operator as friend function

friend ostream& operator<<(ostream& , const Rational& );//Similarly the input operator

//Assignment operators as member functions Rational& operator+=(const Rational& );

//Similarly the remaining assignment operators

private: int nom; int denom; int gcd(int , int ); //input: two integers, returns greatest common devisor void reduce( void ); //reduces nom and denom to smallest value};

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

15

Class Class RationalRational - Definition and Use of Overloaded Output - Definition and Use of Overloaded Output

Prototype in class definition:Prototype in class definition:

friend ostream& operator<<(ostream& , const Rational& );

Definition:Definition:

ostream& operator<<(ostream& out, const Rational& s){out << s.nom << '/' << s.denom ;return out;

}

Use:Use:Rational d( 3, 9 );

cout << "d = " << d << endl;

d = 1/3

Reference as it will change after insertion of expressions to be output

Reference: returns class object, not just object value; thus allowing compound operations

overloadedstream insertion operator

argument1: out argument2: s

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

16

Class Class RationalRational - Definition and Use of Overloaded Assignment - Definition and Use of Overloaded Assignment

Prototype in class definition:Prototype in class definition:

Rational& operator+=(const Rational& );

Definition:Definition:Rational& Rational :: operator+=(const Rational& r){

nom = nom * r.denom + denom * r.nom;denom *= r.denom;reduce();return *this;

}Use:Use:

Rational r(3, 2);Rational r(3, 2);cout<< "r = " << r << endl;cout<< "r = " << r << endl;cout<< r << "+ 2 =";cout<< r << "+ 2 =";r += 2;r += 2;cout<< r << endl;cout<< r << endl;

Refers to object itself, i.e. object that received message and was modified.

r = 3/23/2+ 2 =7/2

Reference: returns class object, not just object value; thus allowing compound operations

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

17

The The thisthis Pointer Gives Access to Object's Own Address Pointer Gives Access to Object's Own Address

Goal: Provide object with the ability to refer to itselfGoal: Provide object with the ability to refer to itself

As shown in the overloaded addition assignment this can be quite useful.

Solution: Each object is provided with a pointer Solution: Each object is provided with a pointer this this that contains the object's that contains the object's address.address.

Note:Note:

• The type of the this pointer is given by the type of the corresponding object.

• The this pointer is not part of the object itself, i.e. it is not reflected in the result of the sizeof operation that returns the size of an object. It is passed into object as an implicit first argument with every non-static message (call) to the object.

• The this pointer is used implicitly or explicitly to reference data members and methods of the class

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and

Operators

18

Operators that Cannot Be OverloadedOperators that Cannot Be Overloaded

Most operators in C++ can be overloaded.

However, the following operators cannot be overloaded

. .* :: ?: sizeof

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

19

7.3. Class 7.3. Class String - String - (i) C - strings(i) C - strings

- String literals (constants):- String literals (constants): sequence of characters enclosed in double quotes, e.g.

"I am a string"The internal representation is an array of characters terminated by the NULL character '\0'. Thus the length of the array is always the string length + 1

- Character arrays - can have variable contents- Character arrays - can have variable contentschar s[] = "error";orchar* ps = "error";

I a m a s t r i n g \0

e r r o r \0

pse r r o r \0

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

20

Why bother with operator overload for strings?Why bother with operator overload for strings?

ButButC++ does not provide any operators that process strings as units!!C++ does not provide any operators that process strings as units!! Thus we need to define our own overloaded operators if we want more comfort Thus we need to define our own overloaded operators if we want more comfort in handling strings!in handling strings!

- - C++ has an extensive library of functionsC++ has an extensive library of functions that becomes accessible by including the header <string.h> , e.g.

char *strcpy(char *s1, const char *s2) copies string s2 into s1. Returns value of s1

char *strcat(char *s1, const char *s2) appends string s2 to string s1. Returns value of s1.

char *strcmp(const char *s1, const char *s2) compares string s1 to string s2. Returns 0 for s1=s2, <0 for s1<s2, and >0 for s1>s2.

size_t strlen(const char *s) returns length of s = number of characters in s not including '\0' .

return type of sizeof operator for arrays, typically unsigned int; sizeof returns the total number of bytes in array

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

21

(ii) (ii) newnew and and delete delete Allocate and Deallocate Memory at Run TimeAllocate and Deallocate Memory at Run Time

Goal: Use and free memory as needed during program execution instead of Goal: Use and free memory as needed during program execution instead of blocking it in a static size array throughout the run of the programblocking it in a static size array throughout the run of the program

Solution: Solution: Operatora) new allocates memory of the required type, provides pointer to it, and calls constructor:

Rational * rationalPtr;rationalPtr = new Rational;

In general:<typeNamePtr> = new <TypeName> ;

b) delete frees the memory allocated by new :delete rationalPtr; //memory allocated to *rationalPtr is freed

In general: delete <typeNamePtr> ;

rationalPtr

nom

denom

0

1

* rationalPtr

Important Note: In order to deallocate an entire array, not just the first element, one needs to use

delete [ ] <arrayPtr> ;Otherwise access to memory is lost, but memory is not freed and cannot be used anymore --> memory leak.

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

22

(iii) A (iii) A User Defined class StringUser Defined class StringStringInterface / Behavior

Construct String object from C-stringConstruct String object from another String object

copy constructorDestruct String object freeing the memory

Assign String (=) object to another String objectAppend Assign (+=) String object to another String objectAppend (+) String object to another String object

Tell its length

Tell its C-string value

Tell the character at a given location overloaded subscripts []

Perform comparisons with other String instances

Perform I/O of String instances

Attributes / Data & Internalsstring value, i.e. the sequence of characters composing the string

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

23

class class String - DefinitionString - Definition

class String {public:

String(const char s[]=""); //constructs deep copy of C-string s String(const String& s); //constructs deep copy of String type s ~String(); //deallocates string memory

String& operator=(const String& rhs); //Assigns deep copy rhs

String& operator+=(const String& rhs); //Appends (catenates) deep copy of rhs

friend String operator+(const String& s, const String& t); //Returns deep copy of s appended with deep copy of t

int length() const; //Returns number of string characters const char* charString() const; //Returns C-string value//Subscripts char& operator[](unsigned i); //Element of variable string at position i char operator[](unsigned i) const; //Element of constant string at position i

Constructors and Constructors and DestructorsDestructors

Append and AssignAccess Member Functions

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

24

class class String - Definition (continued)String - Definition (continued)

friend bool operator==(const String& s, const String& t); friend bool operator!=(const String& s, const String& t); friend bool operator< (const String& s, const String& t); friend bool operator<=(const String& s, const String& t); friend bool operator> (const String& s, const String& t); friend bool operator>=(const String& s, const String& t);

friend istream& operator>>(istream& in, String& s); //Reads <= 999 char to newline; Newline is extracted, but not assigned.

friend ostream& operator<<(ostream& out, const String& s); //Ouputs string s

private: char* info_; //pointer to char, NO dimension defined

};

ComparisonComparison

I/O OperatorsI/O Operators

11/17/2008MET CS 563 - Fall 2008

8.Overloading Functions and Operators 25

class class String - ConstructorsString - Constructors

Prototype in class definition:Prototype in class definition:

String(const char s[]=""); //constructs deep copy of C-string s String(const String& s); //constructs deep copy of String type s

//copy constructor

Definition:Definition:String::String(const char *s) { info_= new char[strlen(s)+1]; //allocates char numbers +1 for '\0' strcpy(info_, s);}

Use:Use: String a("Jane"), b("George");

Definition:Definition:String::String(const String& s) {

info_= new char[strlen(s.info_)+1]; //allocates char numbers +1 for '\0' strcpy(info_, s.info_);}

Use: Use: String c(a);

deep copy means that the C-string is copied to the private array of the object, as opposed to a shallow copy that simply copies the array name i.e. the address of the first element.

In general signature of copy constructor of some class A A(const A&)

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

26

class class String - DestructorString - Destructor

Prototype in class definition:Prototype in class definition:

~String(); //deallocates string memory

Definition:Definition:

String::~String() { delete [] info_; //Deallocates array (of any length!) pointed to by info_

}

Use: Use: Called automatically at end of object life time.

We absolutely need the [] in order to free all memory allocated to the array info_ points to. Omitting it will lead to memory leak

11/17/2008MET CS 563 - Fall 2008

8.Overloading Functions and Operators 27

class class String - Assign and Assign Append Operators Are MembersString - Assign and Assign Append Operators Are MembersPrototype in class definition:Prototype in class definition:

String& operator=(const String& rhs); //Assigns deep copy rhs

String& operator+=(const String& rhs); //Appends(catenates) deep copy of rhs Definitions:Definitions:String& String::operator=(const String& rhs) {

if(this != &rhs) { delete [] info_; info_ = new char[strlen(rhs.info_)+1]; strcpy(info_, rhs.info_);

} return *this;

}

String& String::operator+=(const String& rhs){ char *temp= new char[strlen(info_)+strlen(rhs.info_)+1]; strcpy(temp, info_); strcat(temp, rhs.info_); //catenates s.info_ to temp delete [] info_; //deallocate memory pointed to by info_ info_ = temp; //assign info_ to point to catenation of string return *this;

}Use:Use: a=b; a+=b; //exactly as for any built-in type

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

28

(ii) Second Try: Overloaded (ii) Second Try: Overloaded '+''+' as a as a friendfriend Function of class Rational Function of class Rational

Solution:Solution: Introduce a new type of function that is

• not a member functions but still

• has access to the private data members of the class

Such functions are referred as friend functions and are

• declared within the class as are the member functions, but are differentiated from them through the keyword friend preceding the prototype.

• defined outside the class with no mention to the class of which they are friends, i.e. the class knows who its friends are, but not the outside world.

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

29

class class String - Append Operator (+) Is String - Append Operator (+) Is friendfriend

Prototype in class definition:Prototype in class definition:

friend String operator+(const String& s, const String& t); //Returns deep copy of s appended with deep copy of t

Definition:Definition:

String operator+(const String& s, const String& t)//Returns deep copy of s appended with deep copy of t{

String temp(s); //Copy constructor invoked for temp, temp initialized to s temp += t;//t appended to temp with overloaded += return temp;

}

Use:Use: c = a + b; //exactly as for any built-in type

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

30

class class String - Access Member FunctionsString - Access Member Functions

The methods accessing length and the C-string value of the String class are similar to any other access member functions and pretty unremarkable:

int String::length() const //Returns number of string characters{

return strlen(info_);}

and

const char* String::charString() const//Returns C-string value {

return info_;}

The overload of the subscript, however, is more interesting.

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

31

class class String - Subscripts Member FunctionsString - Subscripts Member Functions

char& String::operator[](unsigned i)//Element of variable string at position i {

if(i<0 || i>strlen(info_)){ cerr<<"Subscript range error"<<endl; exit(1);

} return info_[i];

}

char String::operator[](unsigned i) const //Element of constant string at position i{

cout<<"(returned from constant []) "; if(i<0 || i>strlen(info_)){

cerr<<"Subscript range error"<<endl; exit(1);

} return info_[i];

}

exit(1) terminates program as if it executed normally; used typically for input errors

returns object

returns value

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

32

class class String - Comparison OperatorsString - Comparison Operators

Prototype in class definition:Prototype in class definition:friend bool operator==(const String& s, const String& t);

Definition:Definition:bool operator==(const String& s, const String& t){

int l=s.length(); if( l < t.length())

l=s.length(); for (int i = 0; i<l ; i++)

if(s.info_[i]!=t.info_[i]) return false;

return true;}

Use:Use: bool equal = a == b; //exactly as for any built-in type

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

33

class class String - I/O OperatorsString - I/O Operators

Prototype in class definition:Prototype in class definition:

friend istream& operator>>(istream& in, String& s); //Reads <= 999 char to newline; Newline is extracted, but not assigned.

friend ostream& operator<<(ostream& out, const String& s); //Ouputs string s

Definition:Definition:istream& operator>>(istream& in, String& s)//Reads <= 999 char to newline; Newline is extracted, but not assigned.

{ char buffer[1000]; in.getline(buffer,1000,'\n');//Remove <=999 char from in

//up to and including '\n', store all but '\n' in buffer, append '\0' s=String(buffer); return in;

}

ostream& operator<<(ostream& out, const String& s) //Ouputs string s

{ out << s.charString(); return out;

}

Use:Use: cout << a; cin >> b; //exactly as for any built-in type

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

34

class class String Driver – Constructors and EqualityString Driver – Constructors and Equality

void main(){

String a("Jane"), b("George"); cout<<"String a is "<<a<<" of length "<< a.length()<<endl; cout<<"String b is "<<b<<" of length "<< b.length()<<endl;

cout << "String c is constructed with copy constructor with argument string a"

<< endl; String c(a);

cout<<"String c is "<<c<<" of length "<< c.length()<<endl;

String a is Jane of length 4String b is George of length 6String c is constructed with copy constructor with argument string aString c is Jane of length 4

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

35

class class String Driver (continued) - SubscriptsString Driver (continued) - Subscriptscout<< "\nThe positions of the letters in string a are:"<<endl; for(int i=0; i< a.length(); i++)

cout << "Position "<< i << " holds " << a[i] <<endl; cout<< "\nThe positions of the letters in string b are:"<<endl; for(i=0; i< b.length(); i++)

cout << "Position "<< i << " holds " << b[i] <<endl;if(a==b)

cout<<"\nStrings a and b are equal"<<endl; else

cout<<"\nStrings a and b are not equal"<<endl;The positions of the letters in string a are:Position 0 holds JPosition 1 holds aPosition 2 holds nPosition 3 holds e

The positions of the letters in string b are:Position 0 holds GPosition 1 holds ePosition 2 holds oPosition 3 holds rPosition 4 holds gPosition 5 holds e

Strings a and b are not equal

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

36

class class String Driver (continued)- Subscripts for String Driver (continued)- Subscripts for const const ObjectsObjects

const String message("Careful!!"); cout<<"The message is "<<message<<" of length "<< message.length()<<endl;

cout<< "\nThe positions of the letters in the message are:"<<endl; for(i=0; i< message.length(); i++)

cout << "Position "<< i << " holds " << message[i] <<endl;

The message is Careful!! of length 9

The positions of the letters in the message are:(returned from constant []) Position 0 holds C(returned from constant []) Position 1 holds a(returned from constant []) Position 2 holds r(returned from constant []) Position 3 holds e(returned from constant []) Position 4 holds f(returned from constant []) Position 5 holds u(returned from constant []) Position 6 holds l(returned from constant []) Position 7 holds !(returned from constant []) Position 8 holds !

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

37

class class String Driver (continued) – I/OString Driver (continued) – I/O

String friendList[5]; cout<<"\nBegin input for list of five friends:"<<endl; for(i=0; i<5 ; i++){

cout<<"Enter name "<< i+1 <<":"; cin>>friendList[i];

}cout<<"\n Your list of five friends contains:"<<endl; for(i=0; i<5 ; i++){

cout<<" >"<<friendList[i]<<" and the length is " << friendList[i].length() <<endl;

}}//end main()

Begin input for list of five friends:Enter name 1:Jane BrownEnter name 2:David MonroeEnter name 3:Mary SimmonsEnter name 4:Sam VoigtEnter name 5:Steve Cushing

Your list of five friends contains: >Jane Brown and the length is 10 >David Monroe and the length is 12 >Mary Simmons and the length is 12 >Sam Voigt and the length is 9 >Steve Cushing and the length is 13

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

38

Overload - Summary• An overloaded function is a set of functions with the same name and different

argument lists

• An overloaded operator is a C++ operator that has been extended through an additional definition to manipulate user defined and aggregate types in the same way as built-in types.

• To overload an operator a function with the name

operator<OperatorSymbol> ,

where operator is a keyword, must be defined.

• Friend functions of a class are functions that are not member functions but have access to the private data members of the class.

• Friend functions are declared within the class with the keyword friend preceding the function prototype, and are defined outside the class as a regular function, with no indication of their friendship relation to any class.

11/17/2008 MET CS 563 - Fall 2008 8.Overloading Functions and Operators

39

Overload – Summary (continued)• Operator overload can be implemented as a member function or a friend

function:

- overloaded binary operators (arithmetic and comparison) are implemented as friends in order to treat both their arguments in the same way;

- overloaded assignment operators are implemented as member functions returning objects instead of values;

- overloaded I/O operators are implemented as friend functions returning objects instead of values.

• Strings are implemented as character arrays terminating with the NULL character '\0'.

• User-defined classes with overloaded functions and operators make working with the user-defined and aggregate type objects as easy as working with simple built-in type such as integers.

• The operators new and delete allocate and deallocate memory at run time.

A final note:A final note: From this point on read as much code as possible and focus on design rather than on syntax.