SlideShare a Scribd company logo
1 
Chapter 8 - Operator Overloading 
Outline 
8.1 Introduction 
8.2 Fundamentals of Operator Overloading 
8.3 Restrictions on Operator Overloading 
8.4 Operator Functions as Class Members vs. as friend Functions 
8.5 Overloading Stream-Insertion and Stream-Extraction Operators 
8.6 Overloading Unary Operators 
8.7 Overloading Binary Operators 
8.8 Case Study: Array Class 
8.9 Converting between Types 
8.10 Case Study: A String Class 
8.11 Overloading ++ and -- 
8.12 Case Study: A Date Class 
8.13 Standard Library Classes string and vector
2 
8.1 Introduction 
 Use operators with objects (operator 
overloading) 
- Clearer than function calls for certain classes 
- Operator sensitive to context 
 Examples 
– << 
 Stream insertion, bitwise left-shift 
– + 
 Performs arithmetic on multiple types (integers, floats, 
etc.) 
 Will discuss when to use operator overloading
3 
8.2 Fundamentals of Operator 
Overloading 
 Types 
- Built in (int, char) or user-defined 
- Can use existing operators with user-defined types 
 Cannot create new operators 
 Overloading operators 
- Create a function for the class 
- Name function operator followed by symbol 
• Operator+ for the addition operator +
4 
8.2 Fundamentals of Operator 
Overloading 
 Using operators on a class object 
- It must be overloaded for that class 
 Exceptions: 
 Assignment operator, = 
- Memberwise assignment between objects 
 Address operator, & 
- Returns address of object 
 Both can be overloaded 
 Overloading provides concise notation 
– object2 = object1.add(object2); 
– object2 = object2 + object1;
5 
8.3 Restrictions on Operator 
Overloading 
 Cannot change 
- How operators act on built-in data types 
 I.e., cannot change integer addition 
- Precedence of operator (order of evaluation) 
 Use parentheses to force order-of-operations 
- Associativity (left-to-right or right-to-left) 
- Number of operands 
• & is unitary, only acts on one operand 
 Cannot create new operators 
 Operators must be overloaded explicitly 
- Overloading + does not overload +=
6 
8.3 Restrictions on Operator 
Overloading 
Operators that can be overloaded 
+ - * / % ^ & | 
~ ! = < > += -= *= 
/= %= ^= &= |= << >> >>= 
<<= == != <= >= && || ++ 
-- ->* , -> [] () new delete 
new[] delete[] 
Operators that cannot be overloaded 
. .* :: ?: sizeof
7 
8.4 Operator Functions As Class 
Members Vs. As Friend Functions 
 Operator functions 
- Member functions 
 Use this keyword to implicitly get argument 
 Gets left operand for binary operators (like +) 
 Leftmost object must be of same class as operator 
- Non member functions 
 Need parameters for both operands 
 Can have object of different class than operator 
 Must be a friend to access private or 
protected data 
- Called when 
 Left operand of binary operator of same class 
 Single operand of unitary operator of same class
8 
8.4 Operator Functions As Class 
Members Vs. As Friend Functions 
 Overloaded << operator 
- Left operand of type ostream & 
 Such as cout object in cout << classObject 
- Similarly, overloaded >> needs istream & 
- Thus, both must be non-member functions
9 
8.4 Operator Functions As Class 
Members Vs. As Friend Functions 
 Commutative operators 
- May want + to be commutative 
 So both “a + b” and “b + a” work 
- Suppose we have two different classes 
- Overloaded operator can only be member function 
when its class is on left 
• HugeIntClass + Long int 
 Can be member function 
- When other way, need a non-member overload 
function 
• Long int + HugeIntClass
10 
8.5 Overloading Stream-Insertion and 
Stream-Extraction Operators 
• << and >> 
- Already overloaded to process each built-in type 
- Can also process a user-defined class 
 Example program 
- Class PhoneNumber 
 Holds a telephone number 
- Print out formatted number automatically 
• (123) 456-7890
11 
fig08_03.cpp 
(1 of 3) 
1 // Fig. 8.3: fig08_03.cpp 
2 // Overloading the stream-insertion 
and 
3 // stream-extraction operators. 
4 #include <iostream> 
5 
Notice function prototypes for 
overloaded operators >> and << 
They must be non-member friend 
functions, since the object of class 
Phonenumber appears on the right of 
the operator. 
cin << object 
cout >> object 
6 using std::cout; 
7 using std::cin; 
8 using std::endl; 
9 using std::ostream; 
10 using std::istream; 
11 
12 #include <iomanip>
The expression: 
cout << phone; 
is interpreted as the function call: 
operator<<(cout, phone); 
output is an alias for cout. 
This allows objects to be cascaded. 
cout << phone1 << phone2; 
first calls 
operator<<(cout, phone1), and 
returns cout. 
Next, cout << phone2 executes. 
12 
fig08_03.cpp 
(2 of 3) 
27 
28 // overloaded stream-insertion 
operator; cannot be 
29 // a member function if we would 
like to invoke it with 
30 // cout << somePhoneNumber; 
ignore() skips specified 
number of characters from 
31 ostream &operator<<( input (1 by default). 
ostream 
&output, const PhoneNumber &num ) 
32 { 
Stream manipulator setw 
restricts number of characters 
read. setw(4) allows 3 
characters to be read, leaving 
room for the null character. 
33 output << "(" << 
num.areaCode << ") " 
34 << num.exchange << "-"
13 
fig08_03.cpp 
(3 of 3) 
fig08_03.cpp 
output (1 of 1) 
53 
54 } // end function operator>> 
55 
56 int main() 
57 { 
58 PhoneNumber phone; // create 
object phone 
59 
Enter phone number in the form (123) 456-7890: 
(800) 555-1212 
The phone number entered was: (800) 555-1212 
60 cout << "Enter phone number 
in the form (123) 456-7890:n"; 
61 
62 // cin >> phone invokes
14 
8.6 Overloading Unary Operators 
 Overloading unary operators 
- Non-static member function, no arguments 
- Non-member function, one argument 
 Argument must be class object or reference to class 
object 
- Remember, static functions only access static 
data
15 
8.6 Overloading Unary Operators 
 Upcoming example (8.10) 
- Overload ! to test for empty string 
- If non-static member function, needs no 
arguments 
• !s becomes s.operator!() 
class String { 
public: 
bool operator!() const; 
... 
}; 
- If non-member function, needs one argument 
• s! becomes operator!(s) 
class String { 
friend bool operator!( const String & ) 
... 
}
16 
8.7 Overloading Binary Operators 
 Overloading binary operators 
- Non-static member function, one argument 
- Non-member function, two arguments 
 One argument must be class object or reference 
 Upcoming example 
- If non-static member function, needs one 
argument 
class String { 
public: 
const String &operator+=( const String & ); 
... 
}; 
– y += z equivalent to y.operator+=( z )
17 
8.7 Overloading Binary Operators 
 Upcoming example 
- If non-member function, needs two arguments 
- Example: 
class String { 
friend const String &operator+=( 
String &, const String & ); 
... 
}; 
– y += z equivalent to operator+=( y, z )
18 
8.8 Case Study: Array class 
 Arrays in C++ 
- No range checking 
- Cannot be compared meaningfully with == 
- No array assignment (array names const pointers) 
- Cannot input/output entire arrays at once 
 One element at a time 
 Example:Implement an Array class with 
- Range checking 
- Array assignment 
- Arrays that know their size 
- Outputting/inputting entire arrays with << and >> 
- Array comparisons with == and !=
19 
8.8 Case Study: Array class 
 Copy constructor 
- Used whenever copy of object needed 
 Passing by value (return value or parameter) 
 Initializing an object with a copy of another 
– Array newArray( oldArray ); 
– newArray copy of oldArray 
- Prototype for class Array 
• Array( const Array & ); 
 Must take reference 
- Otherwise, pass by value 
- Tries to make copy by calling copy constructor… 
- Infinite loop
array1.h (1 of 2) 
20 
1 // Fig. 8.4: array1.h 
2 // Array class for storing arrays 
of integers. 
3 #ifndef ARRAY1_H 
4 #define ARRAY1_H 
5 
Most operators overloaded as 
member functions (except << 
and >>, which must be non-member 
6 #include <iostream> 
7 
functions). 
8 using std::ostream; 
9 using std::istream; 
10 
Prototype for copy constructor. 
11 class Array { 
12 friend ostream
array1.h (2 of 2) 
21 
27 // inequality operator; returns 
opposite of == operator 
28 bool operator!=( const Array 
&right ) const 
!= operator simply returns 
opposite of == operator. 
Thus, only need to define the 
== operator. 
29 { 
30 return ! ( *this == right ); // 
invokes Array::operator== 
31 
32 } // end function operator!= 
33 
34 // subscript operator for non-const
array1.cpp (1 of 7) 
22 
1 // Fig 8.5: array1.cpp 
2 // Member function definitions for 
class Array 
3 #include <iostream> 
4 
5 using std::cout; 
6 using std::cin; 
7 using std::endl; 
8 
9 #include <iomanip> 
10 
11 using std::setw; 
12
array1.cpp (2 of 7) 
23 
27 for ( int i = 0; i < size; i++ ) 
28 ptr[ i ] = 0; // initialize 
array 
29 
We must declare a new integer array so 
the objects do not point to the same 
memory. 
30 } // end Array default constructor 
31 
32 // copy constructor for class 
Array; 
33 // must receive a reference to 
prevent infinite recursion 
34 Array::Array( const Array 
&arrayToCopy ) 
35 : size( arrayToCopy.size ) 
36 {
array1.cpp (3 of 7) 
24 
51 // return size of array 
52 int Array::getSize() const 
53 { 
Want to avoid self-assignment. 
54 return size; 
55 
56 } // end function getSize 
57 
58 // overloaded assignment 
operator; 
59 // const return avoids: ( a1 = a2 ) 
= a3 
60 const Array 
&Array::operator=( const Array 
&right )
array1.cpp (4 of 7) 
25 
77 
78 return *this; // enables x = y = 
z, for example 
79 
80 } // end function operator= 
81 
82 // determine if two arrays are 
equal and 
83 // return true, otherwise return 
false 
84 bool Array::operator==( const 
Array &right ) const 
85 { 
86 if ( size != right.size )
array1.cpp (5 of 7) 
26 
98 // overloaded subscript operator 
for non-const Arrays 
99 // reference return creates an 
lvalue 
integers1[5] calls 
integers1.operator[]( 5 ) 
100 int &Array::operator[]( int 
exit() (header <cstdlib>) ends 
the program. 
subscript ) 
101 { 
102 // check for subscript out of 
range error 
103 if ( subscript < 0 || subscript >= 
size ) { 
104 cout << "nError: Subscript " 
<< subscript 
105 << " out of range" <<
array1.cpp (6 of 7) 
27 
115 // overloaded subscript operator 
for const Arrays 
116 // const reference return creates 
an rvalue 
117 const int &Array::operator[]( int 
subscript ) const 
118 { 
119 // check for subscript out of 
range error 
120 if ( subscript < 0 || subscript >= 
size ) { 
121 cout << "nError: Subscript " 
<< subscript 
122 << " out of range" <<
array1.cpp (7 of 7) 
28 
142 
143 // overloaded output operator for 
class Array 
144 ostream &operator<<( ostream 
&output, const Array &a ) 
145 { 
146 int i; 
147 
148 // output private ptr-based 
array 
149 for ( i = 0; i < a.size; i++ ) { 
150 output << setw( 12 ) << a.ptr[ 
i ]; 
151
29 
fig08_06.cpp 
(1 of 3) 
1 // Fig. 8.6: fig08_06.cpp 
2 // Array class test program. 
3 #include <iostream> 
4 
5 using std::cout; 
6 using std::cin; 
7 using std::endl; 
8 
9 #include "array1.h" 
10 
11 int main() 
12 { 
13 Array integers1( 7 ); // seven-element
30 
fig08_06.cpp 
(2 of 3) 
26 // input and print integers1 and 
integers2 
27 cout << "nInput 17 
integers:n"; 
28 cin >> integers1 >> integers2; 
29 
30 cout << "nAfter input, the 
arrays contain:n" 
31 << "integers1:n" << 
integers1 
32 << "integers2:n" << 
integers2; 
33 
34 // use overloaded inequality (!
31 
fig08_06.cpp 
(3 of 3) 
48 // use overloaded assignment 
(=) operator 
49 cout << "nAssigning integers2 
to integers1:n"; 
50 integers1 = integers2; // note 
target is smaller 
51 
52 cout << "integers1:n" << 
integers1 
53 << "integers2:n" << 
integers2; 
54 
55 // use overloaded equality (==) 
operator
32 
fig08_06.cpp 
output (1 of 3) 
Size of array integers1 is 7 
Array after initialization: 
0 0 0 0 
0 0 0 
Size of array integers2 is 10 
Array after initialization: 
0 0 0 0 
0 0 0 0 
0 0 
Input 17 integers:
33 
fig08_06.cpp 
output (2 of 3) 
Evaluating: integers1 != integers2 
integers1 and integers2 are not equal 
Size of array integers3 is 7 
Array after initialization: 
1 2 3 4 
5 6 7 
Assigning integers2 to integers1: 
integers1: 
8 9 10 11 
12 13 14 15 
16 17
34 
fig08_06.cpp 
output (3 of 3) 
Assigning 1000 to integers1[5] 
integers1: 
8 9 10 11 
12 1000 14 15 
16 17 
Attempt to assign 1000 to 
integers1[15] 
Error: Subscript 15 out of range
35 
8.9 Converting between Types 
 Casting 
- Traditionally, cast integers to floats, etc. 
- May need to convert between user-defined types 
 Cast operator (conversion operator) 
- Convert from 
 One class to another 
 Class to built-in type (int, char, etc.) 
- Must be non-static member function 
 Cannot be friend 
- Do not specify return type 
 Implicitly returns type to which you are converting
36 
8.9 Converting between Types 
 Example 
- Prototype 
A::operator char *() const; 
 Casts class A to a temporary char * 
• (char *)s calls s.operator char*() 
- Also 
• A::operator int() const; 
• A::operator OtherClass() const;
37 
8.9 Converting between Types 
 Casting can prevent need for overloading 
- Suppose class String can be cast to char * 
– cout << s; // s is a String 
• Compiler implicitly converts s to char * 
• Do not have to overload << 
- Compiler can only do 1 cast
38 
8.10 Case Study: A String Class 
 Build class String 
- String creation, manipulation 
- Class string in standard library (more Chapter 
15) 
 Conversion constructor 
- Single-argument constructor 
- Turns objects of other types into class objects 
• String s1(“hi”); 
 Creates a String from a char * 
- Any single-argument constructor is a conversion 
constructor
string1.h (1 of 3) 
39 
1 // Fig. 8.7: string1.h 
2 // String class definition. 
3 #ifndef STRING1_H 
4 #define STRING1_H 
5 
Conversion constructor to 
make a String from a char 
*. 
6 #include <iostream> 
7 
s1 += s2 interpreted as 
s1.operator+=(s2) 
Can also concatenate a String 
and a char * because the 
compiler will cast the char * 
argument to a String. 
However, it can only do 1 level 
of casting. 
8 using std::ostream; 
9 using std::istream; 
10 
11 class String { 
12 friend ostream 
&operator<<( ostream &, const String
string1.h (2 of 3) 
40 
27 // test s1 != s2 
28 bool operator!=( const String & 
right ) const 
29 { 
30 return !( *this == right ); 
31 
32 } // end function operator!= 
33 
34 // test s1 > s2 
35 bool operator>( const String 
&right ) const
string1.h (3 of 3) 
41 
54 
Two overloaded subscript 
operators, for const and 
non-const objects. 
55 char &operator[] 
( int ); // subscript operator 
56 const char &operator[]( int ) 
Overload the function call 
operator () to return a 
substring. This operator can 
have any amount of operands. 
const; // subscript operator 
57 
58 String operator()( int, 
int ); // return a substring 
59 
60 int getLength() 
const; // return string length 
61 
62 private: 
63 int length; // string length
string1.cpp (1 of 8) 
42 
1 // Fig. 8.8: string1.cpp 
2 // Member function definitions for 
class String. 
3 #include <iostream> 
4 
5 using std::cout; 
6 using std::endl; 
7 
8 #include <iomanip> 
9 
10 using std::setw; 
11 
12 #include <new> // C++
string1.cpp (2 of 8) 
43 
27 
28 // copy constructor 
29 String::String( const String 
&copy ) 
30 : length( copy.length ) 
31 { 
32 cout << "Copy constructor: " 
<< copy.sPtr << 'n'; 
33 setString( copy.sPtr ); // call 
utility function 
34 
35 } // end String copy constructor 
36
string1.cpp (3 of 8) 
44 
55 
56 else 
57 cout << "Attempted 
assignment of a String to itselfn"; 
58 
59 return *this; // enables 
cascaded assignments 
60 
61 } // end function operator= 
62 
63 // concatenate right operand to 
this object and 
64 // store in this object.
string1.cpp (4 of 8) 
45 
81 // is this String empty? 
82 bool String::operator!() const 
83 { 
84 return length == 0; 
85 
86 } // end function operator! 
87 
88 // is this String equal to right 
String? 
89 bool String::operator==( const 
String &right ) const 
90 { 
91 return strcmp( sPtr, right.sPtr )
string1.cpp (5 of 8) 
46 
102 // return reference to character 
in String as lvalue 
103 char &String::operator[]( int 
subscript ) 
104 { 
105 // test for subscript out of 
range 
106 if ( subscript < 0 || subscript >= 
length ) { 
107 cout << "Error: Subscript " 
<< subscript 
108 << " out of range" << 
endl; 
109
string1.cpp (6 of 8) 
47 
131 
132 // return a substring beginning at 
index and 
133 // of length subLength 
134 String String::operator()( int 
index, int subLength ) 
135 { 
136 // if index is out of range or 
substring length < 0, 
137 // return an empty String object 
138 if ( index < 0 || index >= length 
|| subLength < 0 ) 
139 return ""; // converted to a 
String object automatically
string1.cpp (7 of 8) 
48 
156 
157 // create temporary String 
object containing the substring 
158 String tempString( tempPtr ); 
159 delete [] tempPtr; // delete 
temporary array 
160 
161 return tempString; // return 
copy of the temporary String 
162 
163 } // end function operator() 
164 
165 // return string length
string1.cpp (8 of 8) 
49 
179 
180 // overloaded output operator 
181 ostream &operator<<( ostream 
&output, const String &s ) 
182 { 
183 output << s.sPtr; 
184 
185 return output; // enables 
cascading 
186 
187 } // end function operator<< 
188 
189 // overloaded input operator
50 
fig08_09.cpp 
(1 of 4) 
1 // Fig. 8.9: fig08_09.cpp 
2 // String class test program. 
3 #include <iostream> 
4 
5 using std::cout; 
6 using std::endl; 
7 
8 #include "string1.h" 
9 
10 int main() 
11 { 
12 String s1( "happy" ); 
13 String s2( " birthday" );
51 
fig08_09.cpp 
(2 of 4) 
26 << "ns2 < s1 yields " 
27 << ( s2 < s1 ? "true" : 
"false" ) 
28 << "ns2 >= s1 yields " 
29 << ( s2 >= s1 ? "true" : 
"false" ) 
30 << "ns2 <= s1 yields " 
31 << ( s2 <= s1 ? "true" : 
"false" ); 
32 
33 // test overloaded String empty 
(!) operator 
34 cout << "nnTesting !s3:n"; 
35
52 
fig08_09.cpp 
(3 of 4) 
51 
52 // test overloaded function call 
operator () for substring 
53 cout << "The substring of s1 
starting atn" 
54 << "location 0 for 14 
characters, s1(0, 14), is:n" 
55 << s1( 0, 14 ) << "nn"; 
56 
57 // test substring "to-end-of- 
String" option 
58 cout << "The substring of s1 
starting atn" 
59 << "location 15, s1(15, 0),
53 
fig08_09.cpp 
(4 of 4) 
74 // test using subscript operator 
to create lvalue 
75 s1[ 0 ] = 'H'; 
76 s1[ 6 ] = 'B'; 
77 cout << "ns1 after s1[0] = 'H' 
and s1[6] = 'B' is: " 
78 << s1 << "nn"; 
79 
80 // test subscript out of range 
81 cout << "Attempt to assign 'd'
54 
fig08_09.cpp 
(1 of 3) 
Conversion constructor: happy 
Conversion constructor: birthday 
Conversion constructor: 
s1 is "happy"; s2 is " birthday"; s3 is 
"" 
The results of comparing s2 and s1: 
s2 == s1 yields false 
s2 != s1 yields true 
s2 > s1 yields false 
s2 < s1 yields true 
s2 >= s1 yields false 
s2 <= s1 yields true 
The constructor and 
destructor are called for the 
temporary String 
(converted from the char * 
“to you”).
55 
fig08_09.cpp 
(2 of 3) 
Conversion constructor: happy 
birthday 
Copy constructor: happy birthday 
Destructor: happy birthday 
The substring of s1 starting at 
location 0 for 14 characters, s1(0, 
14), is: 
happy birthday 
Destructor: happy birthday 
Conversion constructor: to you 
Copy constructor: to you 
Destructor: to you
56 
fig08_09.cpp 
(3 of 3) 
s1 after s1[0] = 'H' and s1[6] = 'B' is: 
Happy Birthday to you 
Attempt to assign 'd' to s1[30] yields: 
Error: Subscript 30 out of range
57 
8.11 Overloading ++ and -- 
 Increment/decrement operators can be 
overloaded 
- Add 1 to a Date object, d1 
- Prototype (member function) 
• Date &operator++(); 
• ++d1 same as d1.operator++() 
- Prototype (non-member) 
• Friend Date &operator++( Date &); 
• ++d1 same as operator++( d1 )
58 
8.11 Overloading ++ and -- 
 To distinguish pre/post increment 
- Post increment has a dummy parameter 
• int of 0 
- Prototype (member function) 
• Date operator++( int ); 
• d1++ same as d1.operator++( 0 ) 
- Prototype (non-member) 
• friend Date operator++( Data &, int ); 
• d1++ same as operator++( d1, 0 ) 
- Integer parameter does not have a name 
 Not even in function definition
59 
8.11 Overloading ++ and -- 
 Return values 
- Preincrement 
 Returns by reference (Date &) 
 lvalue (can be assigned) 
- Postincrement 
 Returns by value 
 Returns temporary object with old value 
 rvalue (cannot be on left side of assignment) 
 Decrement operator analogous
60 
8.12 Case Study: A Date Class 
 Example Date class 
- Overloaded increment operator 
 Change day, month and year 
- Overloaded += operator 
- Function to test for leap years 
- Function to determine if day is last of month
61 
date1.h (1 of 2) 
1 // Fig. 8.10: date1.h 
2 // Date class definition. 
3 #ifndef DATE1_H 
4 #define DATE1_H 
5 #include <iostream> 
6 
7 using std::ostream; 
8 
9 class Date { 
10 friend ostream 
&operator<<( ostream &, const Date 
& ); 
11 
Note difference between pre 
and post increment.
62 
date1.h (2 of 2) 
23 
24 private: 
25 int month; 
26 int day; 
27 int year; 
28 
29 static const int days[]; // 
array of days per month 
30 void helpIncrement(); // 
utility function 
31 
32 }; // end class Date 
33
date1.cpp (1 of 5) 
63 
1 // Fig. 8.11: date1.cpp 
2 // Date class member function 
definitions. 
3 #include <iostream> 
4 #include "date1.h" 
5 
6 // initialize static member at file 
scope; 
7 // one class-wide copy 
8 const int Date::days[] = 
9 { 0, 31, 28, 31, 30, 31, 30, 31, 
31, 30, 31, 30, 31 }; 
10
date1.cpp (2 of 5) 
64 
24 // test for a leap year 
25 if ( month == 2 && 
leapYear( year ) ) 
26 day = ( dd >= 1 && dd <= 
29 ) ? dd : 1; 
27 else 
28 day = ( dd >= 1 && dd <= 
Postincrement updates object 
and returns a copy of the 
original. Do not return a 
reference to temp, because it 
is a local variable that will be 
destroyed. 
Also note that the integer 
parameter does not have a 
name. 
days[ month ] ) ? dd : 1; 
29 
30 } // end function setDate 
31 
32 // overloaded preincrement 
operator 
33 Date &Date::operator++()
date1.cpp (3 of 5) 
65 
52 
53 // add specified number of days 
to date 
54 const Date 
&Date::operator+=( int additionalDays 
) 
55 { 
56 for ( int i = 0; i < 
additionalDays; i++ ) 
57 helpIncrement(); 
58 
59 return *this; // enables 
cascading 
60
date1.cpp (4 of 5) 
66 
75 // determine whether the day is 
the last day of the month 
76 bool Date::endOfMonth( int 
testDay ) const 
77 { 
78 if ( month == 2 && 
leapYear( year ) ) 
79 return testDay == 29; // last 
day of Feb. in leap year 
80 else 
81 return testDay == 
days[ month ]; 
82 
83 } // end function endOfMonth
date1.cpp (5 of 5) 
67 
100 // last day of year 
101 else { 
102 ++year; 
103 month = 1; 
104 day = 1; 
105 } 
106 
107 } // end function helpIncrement 
108 
109 // overloaded output operator 
110 ostream &operator<<( ostream 
&output, const Date &d ) 
111 {
68 
fig08_12.cpp 
(1 of 2) 
1 // Fig. 8.12: fig08_12.cpp 
2 // Date class test program. 
3 #include <iostream> 
4 
5 using std::cout; 
6 using std::endl; 
7 
8 #include "date1.h" // Date class 
definition 
9 
10 int main() 
11 { 
12 Date d1; // defaults to January
69 
fig08_12.cpp 
(2 of 2) 
26 
27 cout << "nnTesting the 
preincrement operator:n" 
28 << " d4 is " << d4 << 'n'; 
29 cout << "++d4 is " << ++d4 << 
'n'; 
30 cout << " d4 is " << d4; 
31 
32 cout << "nnTesting the 
postincrement operator:n" 
33 << " d4 is " << d4 << 'n';
70 
fig08_12.cpp 
output (1 of 1) 
d1 is January 1, 1900 
d2 is December 27, 1992 
d3 is January 1, 1900 
d2 += 7 is January 3, 1993 
d3 is February 28, 1992 
++d3 is February 29, 1992 
Testing the preincrement operator: 
d4 is July 13, 2002 
++d4 is July 14, 2002 
d4 is July 14, 2002
71 
8.13Standard Library Classes 
string and vector 
 Classes built into C++ 
- Available for anyone to use 
– string 
 Similar to our String class 
– vector 
 Dynamically resizable array 
 Redo our String and Array examples 
- Use string and vector
72 
8.13Standard Library Classes 
string and vector 
 Class string 
- Header <string>, namespace std 
- Can initialize string s1(“hi”); 
- Overloaded << 
• cout << s1 
- Overloaded relational operators 
• == != >= > <= < 
- Assignment operator = 
- Concatenation (overloaded +=)
73 
8.13Standard Library Classes 
string and vector 
 Class string 
- Substring function substr 
• s1.substr(0, 14); 
- Starts at location 0, gets 14 characters 
• S1.substr(15) 
- Substring beginning at location 15 
- Overloaded [] 
 Access one character 
 No range checking (if subscript invalid) 
– at function 
• s1.at(10) 
 Character at subscript 10 
 Has bounds checking 
- Will end program if invalid (learn more in Chapter 13)
74 
fig08_13.cpp 
(1 of 4) 
1 // Fig. 8.13: fig08_13.cpp 
2 // Standard library string class 
test program. 
3 #include <iostream> 
4 
5 using std::cout; 
6 using std::endl; 
7 
8 #include <string> 
9 
10 using std::string; 
11 
12 int main()
75 
fig08_13.cpp 
(2 of 4) 
26 << "ns2 > s1 yields " 
27 << ( s2 > s1 ? "true" : 
"false" ) 
28 << "ns2 < s1 yields " 
29 << ( s2 < s1 ? "true" : 
"false" ) 
30 << "ns2 >= s1 yields " 
31 << ( s2 >= s1 ? "true" : 
"false" ) 
32 << "ns2 <= s1 yields " 
33 << ( s2 <= s1 ? "true" : 
"false" ); 
34 
35 // test string member function
76 
fig08_13.cpp 
(3 of 4) 
49 // test overloaded string 
concatenation operator 
50 // with C-style string 
51 cout << "nns1 += " to you" 
yieldsn"; 
52 s1 += " to you"; 
53 cout << "s1 = " << s1 << "nn"; 
54 
55 // test string member function 
substr 
56 cout << "The substring of s1 
starting at location 0 forn" 
57 << "14 characters, 
s1.substr(0, 14), is:n"
77 
fig08_13.cpp 
(4 of 4) 
74 // test destructor 
75 delete s4Ptr; 
76 
77 // test using subscript operator 
to create lvalue 
78 s1[ 0 ] = 'H'; 
79 s1[ 6 ] = 'B'; 
80 cout << "ns1 after s1[0] = 'H' 
and s1[6] = 'B' is: " 
81 << s1 << "nn"; 
82 
83 // test subscript out of range 
with string member function "at"
78 
fig08_13.cpp 
output (1 of 2) 
s1 is "happy"; s2 is " birthday"; s3 is 
"" 
The results of comparing s2 and s1: 
s2 == s1 yields false 
s2 != s1 yields true 
s2 > s1 yields false 
s2 < s1 yields true 
s2 >= s1 yields false 
s2 <= s1 yields true 
Testing s3.empty(): 
s3 is empty; assigning s1 to s3;
79 
fig08_13.cpp 
output (2 of 2) 
The substring of s1 starting at 
location 15, s1.substr(15), is: 
to you 
*s4Ptr = happy birthday to you 
assigning *s4Ptr to *s4Ptr 
*s4Ptr = happy birthday to you 
s1 after s1[0] = 'H' and s1[6] = 'B' is: 
Happy Birthday to you 
Attempt to assign 'd' to s1.at( 30 )
80 
8.13Standard Library Classes 
string and vector 
 Class vector 
- Header <vector>, namespace std 
- Store any type 
• vector< int > myArray(10) 
- Function size ( myArray.size() ) 
- Overloaded [] 
 Get specific element, myArray[3] 
- Overloaded !=, ==, and = 
 Inequality, equality, assignment
81 
fig08_14.cpp 
(1 of 5) 
1 // Fig. 8.14: fig08_14.cpp 
2 // Demonstrating standard library 
class vector. 
3 #include <iostream> 
4 
5 using std::cout; 
6 using std::cin; 
7 using std::endl; 
8 
9 #include <iomanip> 
10 
11 using std::setw; 
12
82 
fig08_14.cpp 
(2 of 5) 
25 // print integers1 size and 
contents 
26 cout << "Size of vector 
integers1 is " 
27 << integers1.size() 
28 << "nvector after 
initialization:n"; 
29 outputVector( integers1 ); 
30 
31 // print integers2 size and 
contents 
32 cout << "nSize of vector 
integers2 is " 
33 << integers2.size()
83 
fig08_14.cpp 
(3 of 5) 
51 if ( integers1 != integers2 ) 
52 cout << "integers1 and 
integers2 are not equaln"; 
53 
54 // create vector integers3 using 
integers1 as an 
55 // initializer; print size and 
contents 
56 vector< int > 
integers3( integers1 ); // copy 
constructor 
57 
58 cout << "nSize of vector 
integers3 is "
84 
fig08_14.cpp 
(4 of 5) 
73 // use overloaded equality (==) 
operator 
74 cout << "nEvaluating: 
integers1 == integers2n"; 
75 
76 if ( integers1 == integers2 ) 
77 cout << "integers1 and 
integers2 are equaln"; 
78 
79 // use overloaded subscript 
operator to create rvalue 
80 cout << "nintegers1[5] is " << 
integers1[ 5 ]; 
81
85 
fig08_14.cpp 
(5 of 5) 
97 // output vector contents 
98 void outputVector( const vector< 
int > &array ) 
99 { 
100 for ( int i = 0; i < array.size(); i+ 
+ ) { 
101 cout << setw( 12 ) << array[ i 
]; 
102 
103 if ( ( i + 1 ) % 4 == 0 ) // 4 
numbers per row of output 
104 cout << endl; 
105 
106 } // end for
86 
fig08_14.cpp 
output (1 of 2) 
Size of vector integers1 is 7 
vector after initialization: 
0 0 0 0 
0 0 0 
Size of vector integers2 is 10 
vector after initialization: 
0 0 0 0 
0 0 0 0 
0 0 
Input 17 integers: 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
87 
fig08_14.cpp 
output (2 of 2) 
Size of vector integers3 is 7 
vector after initialization: 
1 2 3 4 
5 6 7 
Assigning integers2 to integers1: 
integers1: 
8 9 10 11 
12 13 14 15 
16 17 
integers2: 
8 9 10 11 
12 13 14 15

More Related Content

PPT
Operator overloading
PPT
Operator overloading
PPTX
Operator Overloading & Type Conversions
PPT
14 operator overloading
PPTX
PPT
Java 8 Streams
PPTX
Operator overloading
PPTX
Operator overloading
Operator overloading
Operator overloading
Operator Overloading & Type Conversions
14 operator overloading
Java 8 Streams
Operator overloading
Operator overloading

What's hot (20)

PPTX
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
PPTX
operator overloading
PPTX
operator overloading
PPTX
Unary operator overloading
PPT
Lecture5
PPTX
Operator overloading
PPTX
OPERATOR OVERLOADING IN C++
PPTX
Bca 2nd sem u-4 operator overloading
PPTX
Overloading of io stream operators
PPTX
Operator overloading
PPTX
A Brief Conceptual Introduction to Functional Java 8 and its API
PPT
3d7b7 session4 c++
PDF
Parallel streams in java 8
PDF
Java 8 Stream API. A different way to process collections.
PPT
08 c++ Operator Overloading.ppt
DOCX
Memory management in c++
PPTX
Operator Overloading
PDF
06. operator overloading
PDF
Functional Programming Patterns for the Pragmatic Programmer
PDF
Monads in Swift
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
operator overloading
operator overloading
Unary operator overloading
Lecture5
Operator overloading
OPERATOR OVERLOADING IN C++
Bca 2nd sem u-4 operator overloading
Overloading of io stream operators
Operator overloading
A Brief Conceptual Introduction to Functional Java 8 and its API
3d7b7 session4 c++
Parallel streams in java 8
Java 8 Stream API. A different way to process collections.
08 c++ Operator Overloading.ppt
Memory management in c++
Operator Overloading
06. operator overloading
Functional Programming Patterns for the Pragmatic Programmer
Monads in Swift
Ad

Similar to Synapse india complain sharing info on chapter 8 operator overloading (20)

PPT
lecture12.ppt
PPT
Operator overloading in c++ is the most required.
PPT
OOP OOOOOverloading Concept lecture12.ppt
PPT
operator overloading concept in oops lecture12.ppt
PDF
Lec 8.pdf a
PPTX
Operator overloaing
PPT
Overloading
PPT
Operator overloading
PPTX
Operator overloading
PPT
Operator overloading Object Oriented Programming
PDF
Ch-4-Operator Overloading.pdf
PPTX
2CPP13 - Operator Overloading
PPTX
operator overloading & type conversion in cpp over view || c++
PPTX
operator overloading & type conversion in cpp
PDF
Object Oriented Programming using C++ - Part 3
PDF
Unit3_OOP-converted.pdf
PDF
overloading in C++
PPT
Lec 28 - operator overloading
PPT
Lec 26.27-operator overloading
PDF
Operator overloading
lecture12.ppt
Operator overloading in c++ is the most required.
OOP OOOOOverloading Concept lecture12.ppt
operator overloading concept in oops lecture12.ppt
Lec 8.pdf a
Operator overloaing
Overloading
Operator overloading
Operator overloading
Operator overloading Object Oriented Programming
Ch-4-Operator Overloading.pdf
2CPP13 - Operator Overloading
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp
Object Oriented Programming using C++ - Part 3
Unit3_OOP-converted.pdf
overloading in C++
Lec 28 - operator overloading
Lec 26.27-operator overloading
Operator overloading
Ad

More from SynapseindiaComplaints (11)

PPT
Designing mobile applications
PPT
Introduction to web design
PPT
Synapse india reviews about mobile web development part3
PPT
Synapse india complain sharing info about php chaptr 26
PPT
Synapse india reviews sharing chapter 23 – asp.net
PPT
Synapse india reviews sharing asp.net
PPT
Synapseindia reviews sharing intro on php
PPT
Synapseindia reviews sharing intro cakephp
PPT
Synapseindia reviews sharing intro on php
PPT
Synapse india complaints on windows 8 developer preview pre-beta
ODP
Synapse india complaints on secure web applications
Designing mobile applications
Introduction to web design
Synapse india reviews about mobile web development part3
Synapse india complain sharing info about php chaptr 26
Synapse india reviews sharing chapter 23 – asp.net
Synapse india reviews sharing asp.net
Synapseindia reviews sharing intro on php
Synapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro on php
Synapse india complaints on windows 8 developer preview pre-beta
Synapse india complaints on secure web applications

Recently uploaded (20)

PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Business Ethics Teaching Materials for college
PDF
Complications of Minimal Access Surgery at WLH
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Pharmacology of Heart Failure /Pharmacotherapy of CHF
TR - Agricultural Crops Production NC III.pdf
RMMM.pdf make it easy to upload and study
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Microbial disease of the cardiovascular and lymphatic systems
Business Ethics Teaching Materials for college
Complications of Minimal Access Surgery at WLH
human mycosis Human fungal infections are called human mycosis..pptx
Microbial diseases, their pathogenesis and prophylaxis
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
O7-L3 Supply Chain Operations - ICLT Program
O5-L3 Freight Transport Ops (International) V1.pdf
Basic Mud Logging Guide for educational purpose
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester

Synapse india complain sharing info on chapter 8 operator overloading

  • 1. 1 Chapter 8 - Operator Overloading Outline 8.1 Introduction 8.2 Fundamentals of Operator Overloading 8.3 Restrictions on Operator Overloading 8.4 Operator Functions as Class Members vs. as friend Functions 8.5 Overloading Stream-Insertion and Stream-Extraction Operators 8.6 Overloading Unary Operators 8.7 Overloading Binary Operators 8.8 Case Study: Array Class 8.9 Converting between Types 8.10 Case Study: A String Class 8.11 Overloading ++ and -- 8.12 Case Study: A Date Class 8.13 Standard Library Classes string and vector
  • 2. 2 8.1 Introduction  Use operators with objects (operator overloading) - Clearer than function calls for certain classes - Operator sensitive to context  Examples – <<  Stream insertion, bitwise left-shift – +  Performs arithmetic on multiple types (integers, floats, etc.)  Will discuss when to use operator overloading
  • 3. 3 8.2 Fundamentals of Operator Overloading  Types - Built in (int, char) or user-defined - Can use existing operators with user-defined types  Cannot create new operators  Overloading operators - Create a function for the class - Name function operator followed by symbol • Operator+ for the addition operator +
  • 4. 4 8.2 Fundamentals of Operator Overloading  Using operators on a class object - It must be overloaded for that class  Exceptions:  Assignment operator, = - Memberwise assignment between objects  Address operator, & - Returns address of object  Both can be overloaded  Overloading provides concise notation – object2 = object1.add(object2); – object2 = object2 + object1;
  • 5. 5 8.3 Restrictions on Operator Overloading  Cannot change - How operators act on built-in data types  I.e., cannot change integer addition - Precedence of operator (order of evaluation)  Use parentheses to force order-of-operations - Associativity (left-to-right or right-to-left) - Number of operands • & is unitary, only acts on one operand  Cannot create new operators  Operators must be overloaded explicitly - Overloading + does not overload +=
  • 6. 6 8.3 Restrictions on Operator Overloading Operators that can be overloaded + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[] delete[] Operators that cannot be overloaded . .* :: ?: sizeof
  • 7. 7 8.4 Operator Functions As Class Members Vs. As Friend Functions  Operator functions - Member functions  Use this keyword to implicitly get argument  Gets left operand for binary operators (like +)  Leftmost object must be of same class as operator - Non member functions  Need parameters for both operands  Can have object of different class than operator  Must be a friend to access private or protected data - Called when  Left operand of binary operator of same class  Single operand of unitary operator of same class
  • 8. 8 8.4 Operator Functions As Class Members Vs. As Friend Functions  Overloaded << operator - Left operand of type ostream &  Such as cout object in cout << classObject - Similarly, overloaded >> needs istream & - Thus, both must be non-member functions
  • 9. 9 8.4 Operator Functions As Class Members Vs. As Friend Functions  Commutative operators - May want + to be commutative  So both “a + b” and “b + a” work - Suppose we have two different classes - Overloaded operator can only be member function when its class is on left • HugeIntClass + Long int  Can be member function - When other way, need a non-member overload function • Long int + HugeIntClass
  • 10. 10 8.5 Overloading Stream-Insertion and Stream-Extraction Operators • << and >> - Already overloaded to process each built-in type - Can also process a user-defined class  Example program - Class PhoneNumber  Holds a telephone number - Print out formatted number automatically • (123) 456-7890
  • 11. 11 fig08_03.cpp (1 of 3) 1 // Fig. 8.3: fig08_03.cpp 2 // Overloading the stream-insertion and 3 // stream-extraction operators. 4 #include <iostream> 5 Notice function prototypes for overloaded operators >> and << They must be non-member friend functions, since the object of class Phonenumber appears on the right of the operator. cin << object cout >> object 6 using std::cout; 7 using std::cin; 8 using std::endl; 9 using std::ostream; 10 using std::istream; 11 12 #include <iomanip>
  • 12. The expression: cout << phone; is interpreted as the function call: operator<<(cout, phone); output is an alias for cout. This allows objects to be cascaded. cout << phone1 << phone2; first calls operator<<(cout, phone1), and returns cout. Next, cout << phone2 executes. 12 fig08_03.cpp (2 of 3) 27 28 // overloaded stream-insertion operator; cannot be 29 // a member function if we would like to invoke it with 30 // cout << somePhoneNumber; ignore() skips specified number of characters from 31 ostream &operator<<( input (1 by default). ostream &output, const PhoneNumber &num ) 32 { Stream manipulator setw restricts number of characters read. setw(4) allows 3 characters to be read, leaving room for the null character. 33 output << "(" << num.areaCode << ") " 34 << num.exchange << "-"
  • 13. 13 fig08_03.cpp (3 of 3) fig08_03.cpp output (1 of 1) 53 54 } // end function operator>> 55 56 int main() 57 { 58 PhoneNumber phone; // create object phone 59 Enter phone number in the form (123) 456-7890: (800) 555-1212 The phone number entered was: (800) 555-1212 60 cout << "Enter phone number in the form (123) 456-7890:n"; 61 62 // cin >> phone invokes
  • 14. 14 8.6 Overloading Unary Operators  Overloading unary operators - Non-static member function, no arguments - Non-member function, one argument  Argument must be class object or reference to class object - Remember, static functions only access static data
  • 15. 15 8.6 Overloading Unary Operators  Upcoming example (8.10) - Overload ! to test for empty string - If non-static member function, needs no arguments • !s becomes s.operator!() class String { public: bool operator!() const; ... }; - If non-member function, needs one argument • s! becomes operator!(s) class String { friend bool operator!( const String & ) ... }
  • 16. 16 8.7 Overloading Binary Operators  Overloading binary operators - Non-static member function, one argument - Non-member function, two arguments  One argument must be class object or reference  Upcoming example - If non-static member function, needs one argument class String { public: const String &operator+=( const String & ); ... }; – y += z equivalent to y.operator+=( z )
  • 17. 17 8.7 Overloading Binary Operators  Upcoming example - If non-member function, needs two arguments - Example: class String { friend const String &operator+=( String &, const String & ); ... }; – y += z equivalent to operator+=( y, z )
  • 18. 18 8.8 Case Study: Array class  Arrays in C++ - No range checking - Cannot be compared meaningfully with == - No array assignment (array names const pointers) - Cannot input/output entire arrays at once  One element at a time  Example:Implement an Array class with - Range checking - Array assignment - Arrays that know their size - Outputting/inputting entire arrays with << and >> - Array comparisons with == and !=
  • 19. 19 8.8 Case Study: Array class  Copy constructor - Used whenever copy of object needed  Passing by value (return value or parameter)  Initializing an object with a copy of another – Array newArray( oldArray ); – newArray copy of oldArray - Prototype for class Array • Array( const Array & );  Must take reference - Otherwise, pass by value - Tries to make copy by calling copy constructor… - Infinite loop
  • 20. array1.h (1 of 2) 20 1 // Fig. 8.4: array1.h 2 // Array class for storing arrays of integers. 3 #ifndef ARRAY1_H 4 #define ARRAY1_H 5 Most operators overloaded as member functions (except << and >>, which must be non-member 6 #include <iostream> 7 functions). 8 using std::ostream; 9 using std::istream; 10 Prototype for copy constructor. 11 class Array { 12 friend ostream
  • 21. array1.h (2 of 2) 21 27 // inequality operator; returns opposite of == operator 28 bool operator!=( const Array &right ) const != operator simply returns opposite of == operator. Thus, only need to define the == operator. 29 { 30 return ! ( *this == right ); // invokes Array::operator== 31 32 } // end function operator!= 33 34 // subscript operator for non-const
  • 22. array1.cpp (1 of 7) 22 1 // Fig 8.5: array1.cpp 2 // Member function definitions for class Array 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include <iomanip> 10 11 using std::setw; 12
  • 23. array1.cpp (2 of 7) 23 27 for ( int i = 0; i < size; i++ ) 28 ptr[ i ] = 0; // initialize array 29 We must declare a new integer array so the objects do not point to the same memory. 30 } // end Array default constructor 31 32 // copy constructor for class Array; 33 // must receive a reference to prevent infinite recursion 34 Array::Array( const Array &arrayToCopy ) 35 : size( arrayToCopy.size ) 36 {
  • 24. array1.cpp (3 of 7) 24 51 // return size of array 52 int Array::getSize() const 53 { Want to avoid self-assignment. 54 return size; 55 56 } // end function getSize 57 58 // overloaded assignment operator; 59 // const return avoids: ( a1 = a2 ) = a3 60 const Array &Array::operator=( const Array &right )
  • 25. array1.cpp (4 of 7) 25 77 78 return *this; // enables x = y = z, for example 79 80 } // end function operator= 81 82 // determine if two arrays are equal and 83 // return true, otherwise return false 84 bool Array::operator==( const Array &right ) const 85 { 86 if ( size != right.size )
  • 26. array1.cpp (5 of 7) 26 98 // overloaded subscript operator for non-const Arrays 99 // reference return creates an lvalue integers1[5] calls integers1.operator[]( 5 ) 100 int &Array::operator[]( int exit() (header <cstdlib>) ends the program. subscript ) 101 { 102 // check for subscript out of range error 103 if ( subscript < 0 || subscript >= size ) { 104 cout << "nError: Subscript " << subscript 105 << " out of range" <<
  • 27. array1.cpp (6 of 7) 27 115 // overloaded subscript operator for const Arrays 116 // const reference return creates an rvalue 117 const int &Array::operator[]( int subscript ) const 118 { 119 // check for subscript out of range error 120 if ( subscript < 0 || subscript >= size ) { 121 cout << "nError: Subscript " << subscript 122 << " out of range" <<
  • 28. array1.cpp (7 of 7) 28 142 143 // overloaded output operator for class Array 144 ostream &operator<<( ostream &output, const Array &a ) 145 { 146 int i; 147 148 // output private ptr-based array 149 for ( i = 0; i < a.size; i++ ) { 150 output << setw( 12 ) << a.ptr[ i ]; 151
  • 29. 29 fig08_06.cpp (1 of 3) 1 // Fig. 8.6: fig08_06.cpp 2 // Array class test program. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include "array1.h" 10 11 int main() 12 { 13 Array integers1( 7 ); // seven-element
  • 30. 30 fig08_06.cpp (2 of 3) 26 // input and print integers1 and integers2 27 cout << "nInput 17 integers:n"; 28 cin >> integers1 >> integers2; 29 30 cout << "nAfter input, the arrays contain:n" 31 << "integers1:n" << integers1 32 << "integers2:n" << integers2; 33 34 // use overloaded inequality (!
  • 31. 31 fig08_06.cpp (3 of 3) 48 // use overloaded assignment (=) operator 49 cout << "nAssigning integers2 to integers1:n"; 50 integers1 = integers2; // note target is smaller 51 52 cout << "integers1:n" << integers1 53 << "integers2:n" << integers2; 54 55 // use overloaded equality (==) operator
  • 32. 32 fig08_06.cpp output (1 of 3) Size of array integers1 is 7 Array after initialization: 0 0 0 0 0 0 0 Size of array integers2 is 10 Array after initialization: 0 0 0 0 0 0 0 0 0 0 Input 17 integers:
  • 33. 33 fig08_06.cpp output (2 of 3) Evaluating: integers1 != integers2 integers1 and integers2 are not equal Size of array integers3 is 7 Array after initialization: 1 2 3 4 5 6 7 Assigning integers2 to integers1: integers1: 8 9 10 11 12 13 14 15 16 17
  • 34. 34 fig08_06.cpp output (3 of 3) Assigning 1000 to integers1[5] integers1: 8 9 10 11 12 1000 14 15 16 17 Attempt to assign 1000 to integers1[15] Error: Subscript 15 out of range
  • 35. 35 8.9 Converting between Types  Casting - Traditionally, cast integers to floats, etc. - May need to convert between user-defined types  Cast operator (conversion operator) - Convert from  One class to another  Class to built-in type (int, char, etc.) - Must be non-static member function  Cannot be friend - Do not specify return type  Implicitly returns type to which you are converting
  • 36. 36 8.9 Converting between Types  Example - Prototype A::operator char *() const;  Casts class A to a temporary char * • (char *)s calls s.operator char*() - Also • A::operator int() const; • A::operator OtherClass() const;
  • 37. 37 8.9 Converting between Types  Casting can prevent need for overloading - Suppose class String can be cast to char * – cout << s; // s is a String • Compiler implicitly converts s to char * • Do not have to overload << - Compiler can only do 1 cast
  • 38. 38 8.10 Case Study: A String Class  Build class String - String creation, manipulation - Class string in standard library (more Chapter 15)  Conversion constructor - Single-argument constructor - Turns objects of other types into class objects • String s1(“hi”);  Creates a String from a char * - Any single-argument constructor is a conversion constructor
  • 39. string1.h (1 of 3) 39 1 // Fig. 8.7: string1.h 2 // String class definition. 3 #ifndef STRING1_H 4 #define STRING1_H 5 Conversion constructor to make a String from a char *. 6 #include <iostream> 7 s1 += s2 interpreted as s1.operator+=(s2) Can also concatenate a String and a char * because the compiler will cast the char * argument to a String. However, it can only do 1 level of casting. 8 using std::ostream; 9 using std::istream; 10 11 class String { 12 friend ostream &operator<<( ostream &, const String
  • 40. string1.h (2 of 3) 40 27 // test s1 != s2 28 bool operator!=( const String & right ) const 29 { 30 return !( *this == right ); 31 32 } // end function operator!= 33 34 // test s1 > s2 35 bool operator>( const String &right ) const
  • 41. string1.h (3 of 3) 41 54 Two overloaded subscript operators, for const and non-const objects. 55 char &operator[] ( int ); // subscript operator 56 const char &operator[]( int ) Overload the function call operator () to return a substring. This operator can have any amount of operands. const; // subscript operator 57 58 String operator()( int, int ); // return a substring 59 60 int getLength() const; // return string length 61 62 private: 63 int length; // string length
  • 42. string1.cpp (1 of 8) 42 1 // Fig. 8.8: string1.cpp 2 // Member function definitions for class String. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setw; 11 12 #include <new> // C++
  • 43. string1.cpp (2 of 8) 43 27 28 // copy constructor 29 String::String( const String &copy ) 30 : length( copy.length ) 31 { 32 cout << "Copy constructor: " << copy.sPtr << 'n'; 33 setString( copy.sPtr ); // call utility function 34 35 } // end String copy constructor 36
  • 44. string1.cpp (3 of 8) 44 55 56 else 57 cout << "Attempted assignment of a String to itselfn"; 58 59 return *this; // enables cascaded assignments 60 61 } // end function operator= 62 63 // concatenate right operand to this object and 64 // store in this object.
  • 45. string1.cpp (4 of 8) 45 81 // is this String empty? 82 bool String::operator!() const 83 { 84 return length == 0; 85 86 } // end function operator! 87 88 // is this String equal to right String? 89 bool String::operator==( const String &right ) const 90 { 91 return strcmp( sPtr, right.sPtr )
  • 46. string1.cpp (5 of 8) 46 102 // return reference to character in String as lvalue 103 char &String::operator[]( int subscript ) 104 { 105 // test for subscript out of range 106 if ( subscript < 0 || subscript >= length ) { 107 cout << "Error: Subscript " << subscript 108 << " out of range" << endl; 109
  • 47. string1.cpp (6 of 8) 47 131 132 // return a substring beginning at index and 133 // of length subLength 134 String String::operator()( int index, int subLength ) 135 { 136 // if index is out of range or substring length < 0, 137 // return an empty String object 138 if ( index < 0 || index >= length || subLength < 0 ) 139 return ""; // converted to a String object automatically
  • 48. string1.cpp (7 of 8) 48 156 157 // create temporary String object containing the substring 158 String tempString( tempPtr ); 159 delete [] tempPtr; // delete temporary array 160 161 return tempString; // return copy of the temporary String 162 163 } // end function operator() 164 165 // return string length
  • 49. string1.cpp (8 of 8) 49 179 180 // overloaded output operator 181 ostream &operator<<( ostream &output, const String &s ) 182 { 183 output << s.sPtr; 184 185 return output; // enables cascading 186 187 } // end function operator<< 188 189 // overloaded input operator
  • 50. 50 fig08_09.cpp (1 of 4) 1 // Fig. 8.9: fig08_09.cpp 2 // String class test program. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include "string1.h" 9 10 int main() 11 { 12 String s1( "happy" ); 13 String s2( " birthday" );
  • 51. 51 fig08_09.cpp (2 of 4) 26 << "ns2 < s1 yields " 27 << ( s2 < s1 ? "true" : "false" ) 28 << "ns2 >= s1 yields " 29 << ( s2 >= s1 ? "true" : "false" ) 30 << "ns2 <= s1 yields " 31 << ( s2 <= s1 ? "true" : "false" ); 32 33 // test overloaded String empty (!) operator 34 cout << "nnTesting !s3:n"; 35
  • 52. 52 fig08_09.cpp (3 of 4) 51 52 // test overloaded function call operator () for substring 53 cout << "The substring of s1 starting atn" 54 << "location 0 for 14 characters, s1(0, 14), is:n" 55 << s1( 0, 14 ) << "nn"; 56 57 // test substring "to-end-of- String" option 58 cout << "The substring of s1 starting atn" 59 << "location 15, s1(15, 0),
  • 53. 53 fig08_09.cpp (4 of 4) 74 // test using subscript operator to create lvalue 75 s1[ 0 ] = 'H'; 76 s1[ 6 ] = 'B'; 77 cout << "ns1 after s1[0] = 'H' and s1[6] = 'B' is: " 78 << s1 << "nn"; 79 80 // test subscript out of range 81 cout << "Attempt to assign 'd'
  • 54. 54 fig08_09.cpp (1 of 3) Conversion constructor: happy Conversion constructor: birthday Conversion constructor: s1 is "happy"; s2 is " birthday"; s3 is "" The results of comparing s2 and s1: s2 == s1 yields false s2 != s1 yields true s2 > s1 yields false s2 < s1 yields true s2 >= s1 yields false s2 <= s1 yields true The constructor and destructor are called for the temporary String (converted from the char * “to you”).
  • 55. 55 fig08_09.cpp (2 of 3) Conversion constructor: happy birthday Copy constructor: happy birthday Destructor: happy birthday The substring of s1 starting at location 0 for 14 characters, s1(0, 14), is: happy birthday Destructor: happy birthday Conversion constructor: to you Copy constructor: to you Destructor: to you
  • 56. 56 fig08_09.cpp (3 of 3) s1 after s1[0] = 'H' and s1[6] = 'B' is: Happy Birthday to you Attempt to assign 'd' to s1[30] yields: Error: Subscript 30 out of range
  • 57. 57 8.11 Overloading ++ and --  Increment/decrement operators can be overloaded - Add 1 to a Date object, d1 - Prototype (member function) • Date &operator++(); • ++d1 same as d1.operator++() - Prototype (non-member) • Friend Date &operator++( Date &); • ++d1 same as operator++( d1 )
  • 58. 58 8.11 Overloading ++ and --  To distinguish pre/post increment - Post increment has a dummy parameter • int of 0 - Prototype (member function) • Date operator++( int ); • d1++ same as d1.operator++( 0 ) - Prototype (non-member) • friend Date operator++( Data &, int ); • d1++ same as operator++( d1, 0 ) - Integer parameter does not have a name  Not even in function definition
  • 59. 59 8.11 Overloading ++ and --  Return values - Preincrement  Returns by reference (Date &)  lvalue (can be assigned) - Postincrement  Returns by value  Returns temporary object with old value  rvalue (cannot be on left side of assignment)  Decrement operator analogous
  • 60. 60 8.12 Case Study: A Date Class  Example Date class - Overloaded increment operator  Change day, month and year - Overloaded += operator - Function to test for leap years - Function to determine if day is last of month
  • 61. 61 date1.h (1 of 2) 1 // Fig. 8.10: date1.h 2 // Date class definition. 3 #ifndef DATE1_H 4 #define DATE1_H 5 #include <iostream> 6 7 using std::ostream; 8 9 class Date { 10 friend ostream &operator<<( ostream &, const Date & ); 11 Note difference between pre and post increment.
  • 62. 62 date1.h (2 of 2) 23 24 private: 25 int month; 26 int day; 27 int year; 28 29 static const int days[]; // array of days per month 30 void helpIncrement(); // utility function 31 32 }; // end class Date 33
  • 63. date1.cpp (1 of 5) 63 1 // Fig. 8.11: date1.cpp 2 // Date class member function definitions. 3 #include <iostream> 4 #include "date1.h" 5 6 // initialize static member at file scope; 7 // one class-wide copy 8 const int Date::days[] = 9 { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 10
  • 64. date1.cpp (2 of 5) 64 24 // test for a leap year 25 if ( month == 2 && leapYear( year ) ) 26 day = ( dd >= 1 && dd <= 29 ) ? dd : 1; 27 else 28 day = ( dd >= 1 && dd <= Postincrement updates object and returns a copy of the original. Do not return a reference to temp, because it is a local variable that will be destroyed. Also note that the integer parameter does not have a name. days[ month ] ) ? dd : 1; 29 30 } // end function setDate 31 32 // overloaded preincrement operator 33 Date &Date::operator++()
  • 65. date1.cpp (3 of 5) 65 52 53 // add specified number of days to date 54 const Date &Date::operator+=( int additionalDays ) 55 { 56 for ( int i = 0; i < additionalDays; i++ ) 57 helpIncrement(); 58 59 return *this; // enables cascading 60
  • 66. date1.cpp (4 of 5) 66 75 // determine whether the day is the last day of the month 76 bool Date::endOfMonth( int testDay ) const 77 { 78 if ( month == 2 && leapYear( year ) ) 79 return testDay == 29; // last day of Feb. in leap year 80 else 81 return testDay == days[ month ]; 82 83 } // end function endOfMonth
  • 67. date1.cpp (5 of 5) 67 100 // last day of year 101 else { 102 ++year; 103 month = 1; 104 day = 1; 105 } 106 107 } // end function helpIncrement 108 109 // overloaded output operator 110 ostream &operator<<( ostream &output, const Date &d ) 111 {
  • 68. 68 fig08_12.cpp (1 of 2) 1 // Fig. 8.12: fig08_12.cpp 2 // Date class test program. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include "date1.h" // Date class definition 9 10 int main() 11 { 12 Date d1; // defaults to January
  • 69. 69 fig08_12.cpp (2 of 2) 26 27 cout << "nnTesting the preincrement operator:n" 28 << " d4 is " << d4 << 'n'; 29 cout << "++d4 is " << ++d4 << 'n'; 30 cout << " d4 is " << d4; 31 32 cout << "nnTesting the postincrement operator:n" 33 << " d4 is " << d4 << 'n';
  • 70. 70 fig08_12.cpp output (1 of 1) d1 is January 1, 1900 d2 is December 27, 1992 d3 is January 1, 1900 d2 += 7 is January 3, 1993 d3 is February 28, 1992 ++d3 is February 29, 1992 Testing the preincrement operator: d4 is July 13, 2002 ++d4 is July 14, 2002 d4 is July 14, 2002
  • 71. 71 8.13Standard Library Classes string and vector  Classes built into C++ - Available for anyone to use – string  Similar to our String class – vector  Dynamically resizable array  Redo our String and Array examples - Use string and vector
  • 72. 72 8.13Standard Library Classes string and vector  Class string - Header <string>, namespace std - Can initialize string s1(“hi”); - Overloaded << • cout << s1 - Overloaded relational operators • == != >= > <= < - Assignment operator = - Concatenation (overloaded +=)
  • 73. 73 8.13Standard Library Classes string and vector  Class string - Substring function substr • s1.substr(0, 14); - Starts at location 0, gets 14 characters • S1.substr(15) - Substring beginning at location 15 - Overloaded []  Access one character  No range checking (if subscript invalid) – at function • s1.at(10)  Character at subscript 10  Has bounds checking - Will end program if invalid (learn more in Chapter 13)
  • 74. 74 fig08_13.cpp (1 of 4) 1 // Fig. 8.13: fig08_13.cpp 2 // Standard library string class test program. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 #include <string> 9 10 using std::string; 11 12 int main()
  • 75. 75 fig08_13.cpp (2 of 4) 26 << "ns2 > s1 yields " 27 << ( s2 > s1 ? "true" : "false" ) 28 << "ns2 < s1 yields " 29 << ( s2 < s1 ? "true" : "false" ) 30 << "ns2 >= s1 yields " 31 << ( s2 >= s1 ? "true" : "false" ) 32 << "ns2 <= s1 yields " 33 << ( s2 <= s1 ? "true" : "false" ); 34 35 // test string member function
  • 76. 76 fig08_13.cpp (3 of 4) 49 // test overloaded string concatenation operator 50 // with C-style string 51 cout << "nns1 += " to you" yieldsn"; 52 s1 += " to you"; 53 cout << "s1 = " << s1 << "nn"; 54 55 // test string member function substr 56 cout << "The substring of s1 starting at location 0 forn" 57 << "14 characters, s1.substr(0, 14), is:n"
  • 77. 77 fig08_13.cpp (4 of 4) 74 // test destructor 75 delete s4Ptr; 76 77 // test using subscript operator to create lvalue 78 s1[ 0 ] = 'H'; 79 s1[ 6 ] = 'B'; 80 cout << "ns1 after s1[0] = 'H' and s1[6] = 'B' is: " 81 << s1 << "nn"; 82 83 // test subscript out of range with string member function "at"
  • 78. 78 fig08_13.cpp output (1 of 2) s1 is "happy"; s2 is " birthday"; s3 is "" The results of comparing s2 and s1: s2 == s1 yields false s2 != s1 yields true s2 > s1 yields false s2 < s1 yields true s2 >= s1 yields false s2 <= s1 yields true Testing s3.empty(): s3 is empty; assigning s1 to s3;
  • 79. 79 fig08_13.cpp output (2 of 2) The substring of s1 starting at location 15, s1.substr(15), is: to you *s4Ptr = happy birthday to you assigning *s4Ptr to *s4Ptr *s4Ptr = happy birthday to you s1 after s1[0] = 'H' and s1[6] = 'B' is: Happy Birthday to you Attempt to assign 'd' to s1.at( 30 )
  • 80. 80 8.13Standard Library Classes string and vector  Class vector - Header <vector>, namespace std - Store any type • vector< int > myArray(10) - Function size ( myArray.size() ) - Overloaded []  Get specific element, myArray[3] - Overloaded !=, ==, and =  Inequality, equality, assignment
  • 81. 81 fig08_14.cpp (1 of 5) 1 // Fig. 8.14: fig08_14.cpp 2 // Demonstrating standard library class vector. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include <iomanip> 10 11 using std::setw; 12
  • 82. 82 fig08_14.cpp (2 of 5) 25 // print integers1 size and contents 26 cout << "Size of vector integers1 is " 27 << integers1.size() 28 << "nvector after initialization:n"; 29 outputVector( integers1 ); 30 31 // print integers2 size and contents 32 cout << "nSize of vector integers2 is " 33 << integers2.size()
  • 83. 83 fig08_14.cpp (3 of 5) 51 if ( integers1 != integers2 ) 52 cout << "integers1 and integers2 are not equaln"; 53 54 // create vector integers3 using integers1 as an 55 // initializer; print size and contents 56 vector< int > integers3( integers1 ); // copy constructor 57 58 cout << "nSize of vector integers3 is "
  • 84. 84 fig08_14.cpp (4 of 5) 73 // use overloaded equality (==) operator 74 cout << "nEvaluating: integers1 == integers2n"; 75 76 if ( integers1 == integers2 ) 77 cout << "integers1 and integers2 are equaln"; 78 79 // use overloaded subscript operator to create rvalue 80 cout << "nintegers1[5] is " << integers1[ 5 ]; 81
  • 85. 85 fig08_14.cpp (5 of 5) 97 // output vector contents 98 void outputVector( const vector< int > &array ) 99 { 100 for ( int i = 0; i < array.size(); i+ + ) { 101 cout << setw( 12 ) << array[ i ]; 102 103 if ( ( i + 1 ) % 4 == 0 ) // 4 numbers per row of output 104 cout << endl; 105 106 } // end for
  • 86. 86 fig08_14.cpp output (1 of 2) Size of vector integers1 is 7 vector after initialization: 0 0 0 0 0 0 0 Size of vector integers2 is 10 vector after initialization: 0 0 0 0 0 0 0 0 0 0 Input 17 integers: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  • 87. 87 fig08_14.cpp output (2 of 2) Size of vector integers3 is 7 vector after initialization: 1 2 3 4 5 6 7 Assigning integers2 to integers1: integers1: 8 9 10 11 12 13 14 15 16 17 integers2: 8 9 10 11 12 13 14 15