8/2/2019 Com 102 Lecture 5
1/111
1
22
22O erator
2006 Pearson Education, Inc. All rights reserved.
Overloading;
String and ArrayObjects
8/2/2019 Com 102 Lecture 5
2/111
2
The whole difference between construction andcreation is exactly this:
that a thing constructed can only be loved after it is
constructed; but a thing created is loved before it
exists.
Gilbert Keith Chesterton
2006 Pearson Education, Inc. All rights reserved.
The die is cast. Julius Caesar
Our doctor would never really operate unless it was
necessary. He was just that way. If he didnt needthe money, he wouldnt lay a hand on you.
Herb Shriner
8/2/2019 Com 102 Lecture 5
3/111
3
OBJECTIVESIn this chapter you will learn:
What operator overloading is and how it makes programs morereadable and programming more convenient.
To redefine (overload) operators to work with objects of user-defined classes.
The differences between overloading unary and binary
2006 Pearson Education, Inc. All rights reserved.
.
To convert objects from one class to another class.
When to, and when not to, overload operators.
To create PhoneNumber, Array, String and Date classesthat demonstrate operator overloading.
To use overloaded operators and other member functions ofstandard library class string.
To use keyword explicit to prevent the compiler from usingsingle-argument constructors to perform implicit conversions.
8/2/2019 Com 102 Lecture 5
4/111
4
22.1 Introduction
22.2 Fundamentals of Operator Overloading22.3 Restrictions on Operator Overloading
22.4 Operator Functions as Class Members vs. Global Functions
22.5 Overloading Stream Insertion and Stream Extraction
Operators22.6 Overloading Unary Operators
22.7 Overloading Binary Operators
22.8 Case Stud : ArraArraArraArra Class
2006 Pearson Education, Inc. All rights reserved.
22.9 Converting between Types
22.10 Case Study: StringStringStringString Class
22.11 Overloading ++++++++ and --------
22.12 Case Study: A DateDateDateDate Class
22.13 Standard Library Class stringstringstringstring
22.14 explicitexplicitexplicitexplicit Constructors
22.15 Wrap-Up
8/2/2019 Com 102 Lecture 5
5/111
5
22.1 Introduction
Use operators with objects (operator overloading)
Clearer than function calls for certain classes
Operator sensitive to context
Examples
2006 Pearson Education, Inc. All rights reserved.
Stream insertion, bitwise left-shift
++++
Performs arithmetic on multiple items (integers, floats, etc.)
8/2/2019 Com 102 Lecture 5
6/111
6
22.2 Fundamentals of Operator
Overloading Types for operator overloading
Built in (intintintint, charcharcharchar) or user-defined (classes)
Can use existing operators with user-defined types
Cannot create new operators
2006 Pearson Education, Inc. All rights reserved.
Create a function for the class
Name of operator function
Keyword operatoroperatoroperatoroperator followed by symbol
Example
operator+operator+operator+operator+ for the addition operator ++++
8/2/2019 Com 102 Lecture 5
7/111
7
Software Engineering Observation 22.1
Operator overloading contributes to C++sextensibilityone of the languages mostappealing attributes.
2006 Pearson Education, Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
8/111
8
Good Programming Practice 22.1
Use operator overloading when it makesa program clearer than accomplishingthe same operations with function calls.
2006 Pearson Education, Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
9/111
9
Good Programming Practice 22.2
Overloaded operators should mimic thefunctionality of their built-in counterpartsforexample, the + operator should be overloaded to
2006 Pearson Education, Inc. All rights reserved.
, .or inconsistent use of operator overloading, as thiscan make a program cryptic and difficult to read.
8/2/2019 Com 102 Lecture 5
10/111
10
22.2 Fundamentals of Operator
Overloading (Cont.) Using operators on a class object
It must be overloaded for that class
Exceptions: (can also be overloaded by the programmer) Assignment operator (====)
Memberwise assignment between objects
Address operator (&&&&)
2006 Pearson Education, Inc. All rights reserved.
Returns address of object Comma operator (,,,,)
Evaluates expression to its left then the expression to itsright
Returns the value of the expression to its right
Overloading provides concise notation
object2 = object1.add( object2 );object2 = object1.add( object2 );object2 = object1.add( object2 );object2 = object1.add( object2 );vs.
object2 = object2 + object1;object2 = object2 + object1;object2 = object2 + object1;object2 = object2 + object1;
8/2/2019 Com 102 Lecture 5
11/111
11
22.3 Restrictions on Operator
Overloading Cannot change
Precedence of operator (order of evaluation)
Use parentheses to force order of operators Associativity (left-to-right or right-to-left)
Number of operands
e.g., &&&& is unary, can only act on one operand
2006 Pearson Education, Inc. All rights reserved.
How operators act on built-in data types (i.e., cannot changeinteger addition)
Cannot create new operators
Operators must be overloaded explicitly
Overloading ++++ and ==== does not overload +=+=+=+=
Operator ?:?:?:?: cannot be overloaded
8/2/2019 Com 102 Lecture 5
12/111
12
Common Programming Error 22.1
Attempting to overload a nonoverloadableoperator is a syntax error.
2006 Pearson Education, Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
13/111
13
Operators that can be overloaded
++++ ---- **** //// %%%% ^ &&&& ||||
~~~~ !!!! ==== > +=+=+=+= ----==== *=*=*=*=
/=/=/=/= %=%=%=%= ^=^=^=^= &=&=&=&= |=|=|=|= > >>=>>=>>=>>=
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.1 | Operators that can be overloaded.
[][][][] ()()()() newnewnewnew deletedeletedeletedelete
newnewnewnew[][][][] deletedeletedeletedelete[][][][]
8/2/2019 Com 102 Lecture 5
14/111
14
Operators that cannot be overloaded
2006 Pearson Education, Inc. All rights reserved.
Fig. 22.2 | Operators that cannot be overloaded.
.... .*.*.*.* :::::::: ?:?:?:?:
8/2/2019 Com 102 Lecture 5
15/111
15
Common Programming Error 22.2
Attempting to change the arity of an operatorvia operator overloading is a compilation error.
2006 Pearson Education, Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
16/111
16
Common Programming Error 22.3
Attempting to create new operators via operatoroverloading is a syntax error.
2006 Pearson Education, Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
17/111
17
Software Engineering Observation 22.2
At least one argument of an operator functionmust be an object or reference of a user-definedtype. This prevents programmers from changing
2006 Pearson Education, Inc. All rights reserved.
.
8/2/2019 Com 102 Lecture 5
18/111
18
Common Programming Error 22.4
Attempting to modify how an operator workswith objects of fundamental types is a compilationerror.
2006 Pearson Education, Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
19/111
19
Common Programming Error 22.5
Assuming that overloading an operator suchas + overloads related operators such as += orthat overloading == overloads a related
2006 Pearson Education, Inc. All rights reserved.
.can be overloaded only explicitly; there is noimplicit overloading.
8/2/2019 Com 102 Lecture 5
20/111
20
22.4 Operator Functions as Class
Members vs. Global Members Operator functions
As member functions
Leftmost object must be of same class as operator function
Use thisthisthisthis keyword to implicitly get left operand argument
Operators ()()()(), [][][][], ---->>>> or any assignment operator must be
2006 Pearson Education, Inc. All rights reserved.
overloaded as a class member function Called when
Left operand of binary operator is of this class
Single operand of unary operator is of this class
As global functions
Need parameters for both operands
Can have object of different class than operator
Can be a friendfriendfriendfriend to access privateprivateprivateprivate or protectedprotectedprotectedprotected data
8/2/2019 Com 102 Lecture 5
21/111
21
22.4 Operator Functions as Class
Members vs. Global Members (Cont.) Overloaded
8/2/2019 Com 102 Lecture 5
22/111
22
Performance Tip 22.1
It is possible to overload an operator as a global,non-friendfriendfriendfriend function, but such a functionrequiring access to a classs privateprivateprivateprivate or
2006 Pearson Education, Inc. All rights reserved.
functions provided in that classs publicpublicpublicpublicinterface. The overhead of calling these functionscould cause poor performance, so these functions
can be inlined to improve performance.
8/2/2019 Com 102 Lecture 5
23/111
23
22.4 Operator Functions as Class
Members vs. Global Members (Cont.) Commutative operators
May want ++++ to be commutative
So both a + ba + ba + ba + b and b + ab + ab + ab + a work
Suppose we have two different classes
Overloaded operator can only be member function when its
2006 Pearson Education, Inc. All rights reserved.
class is on left HugeIntClass +HugeIntClass +HugeIntClass +HugeIntClass + long intlong intlong intlong int
Can be member function
When other way, need a global overloaded function
long intlong intlong intlong int + HugeIntClass+ HugeIntClass+ HugeIntClass+ HugeIntClass
8/2/2019 Com 102 Lecture 5
24/111
24
22.5 Overloading Stream Insertion and
Stream Extraction Operators> operators
Already overloaded to process each built-in type
Can also process a user-defined class
Overload using global, friendfriendfriendfriend functions
2006 Pearson Education, Inc. All rights reserved.
Class PhoneNumberPhoneNumberPhoneNumberPhoneNumber
Holds a telephone number
Print out formatted number automatically
(123) 456(123) 456(123) 456(123) 456----7890789078907890
251 // Fig// Fig// Fig// Fig 22222222 3: PhoneNumber h3: PhoneNumber h3: PhoneNumber h3: PhoneNumber h
8/2/2019 Com 102 Lecture 5
25/111
251 // Fig.// Fig.// Fig.// Fig. 22222222.3: PhoneNumber.h.3: PhoneNumber.h.3: PhoneNumber.h.3: PhoneNumber.h
2 // PhoneNumber class definition// PhoneNumber class definition// PhoneNumber class definition// PhoneNumber class definition
3 #ifndef#ifndef#ifndef#ifndefPHONENUMBER_HPHONENUMBER_HPHONENUMBER_HPHONENUMBER_H
4 #define#define#define#definePHONENUMBER_HPHONENUMBER_HPHONENUMBER_HPHONENUMBER_H
5
6 #include#include#include#include
7 usingusingusingusing std::ostream;std::ostream;std::ostream;std::ostream;
8 usingusingusingusing std::istream;std::istream;std::istream;std::istream;
9
10 #include#include#include#include
11 usingusingusingusing std::string;std::string;std::string;std::string;12
13 classclassclassclass PhoneNumberPhoneNumberPhoneNumberPhoneNumber
14 {{{{
15 friendfriendfriendfriend ostream &operator( istream &, PhoneNumber & );
17 privateprivateprivateprivate::::
18 string areaCode;string areaCode;string areaCode;string areaCode; // 3// 3// 3// 3----digit area codedigit area codedigit area codedigit area code
19 string exchange;string exchange;string exchange;string exchange; //////// 3333----digit exchangedigit exchangedigit exchangedigit exchange
20 string line;string line;string line;string line; // 4// 4// 4// 4----digit linedigit linedigit linedigit line
21 };};};}; // end class PhoneNumber// end class PhoneNumber// end class PhoneNumber// end class PhoneNumber
22
23 #endif#endif#endif#endif
Notice function prototypes for overloaded operators
>> and
8/2/2019 Com 102 Lecture 5
26/111
8/2/2019 Com 102 Lecture 5
27/111
8/2/2019 Com 102 Lecture 5
28/111
29
h b i h f ( )ffh b i h f ( )
8/2/2019 Com 102 Lecture 5
29/111
29
Outline
fig22_05.cppfig22_05.cppfig22_05.cppfig22_05.cpp
(2 of 2)
Enter phone number in the form (123) 456Enter phone number in the form (123) 456Enter phone number in the form (123) 456Enter phone number in the form (123) 456----7890:7890:7890:7890:
(800) 555(800) 555(800) 555(800) 555----1212121212121212
The phone number entered was: (800) 555The phone number entered was: (800) 555The phone number entered was: (800) 555The phone number entered was: (800) 555----1212121212121212
2006 Pearson Education,Inc. All rights reserved.
30
8/2/2019 Com 102 Lecture 5
30/111
30
Error-Prevention Tip 22.1
Returning a reference from an overloaded operator function is typically successfulbecause coutcoutcoutcout, cincincincin and most stream objects
2006 Pearson Education, Inc. All rights reserved.
, - .
reference to an automatic variable or othertemporary object is dangerouscreatingdangling references to nonexisting objects.
31
8/2/2019 Com 102 Lecture 5
31/111
31
Software Engineering Observation 22.3
New input/output capabilities for user-definedtypes are added to C++ without modifying C++sstandard input/output library classes. This is
2006 Pearson Education, Inc. All rights reserved.
programming language.
32
8/2/2019 Com 102 Lecture 5
32/111
22.6 Overloading Unary Operators
Overloading unary operators
Can overload as non-staticstaticstaticstatic member function with no
arguments
Can overload as global function with one argument
Argument must be class object or reference to class object
2006 Pearson Education, Inc. All rights reserved.
Remember, staticstaticstaticstatic functions only access staticstaticstaticstatic data
33
8/2/2019 Com 102 Lecture 5
33/111
22.6 Overloading Unary Operators (Cont.)
Upcoming example (Section 22.10)
Overload !!!! to test for empty string
If non-staticstaticstaticstatic member function, needs no arguments
classclassclassclass StringStringStringString{{{{
2006 Pearson Education, Inc. All rights reserved.
pu cpu cpu cpu c::::
bool operatorbool operatorbool operatorbool operator!()!()!()!() constconstconstconst;;;;
};};};};
!s!s!s!s becomes s.s.s.s.operatoroperatoroperatoroperator!()!()!()!()
If global function, needs one argument
boolboolboolbool operatoroperatoroperatoroperator!(!(!(!( constconstconstconst String & )String & )String & )String & )
s!s!s!s! becomes operatoroperatoroperatoroperator!(s)!(s)!(s)!(s)
34
8/2/2019 Com 102 Lecture 5
34/111
22.7 Overloading Binary Operators
Overloading binary operators
Non-staticstaticstaticstatic member function, one argument
Global function, two arguments
One argument must be class object or reference
2006 Pearson Education, Inc. All rights reserved.
35
22 7 O l di Bi O t
8/2/2019 Com 102 Lecture 5
35/111
22.7 Overloading Binary Operators
(Cont.) Upcoming example: Overloading +=+=+=+=
If non-staticstaticstaticstatic member function, needs one argument
classclassclassclass StringStringStringString{{{{publicpublicpublicpublic::::
constconstconstconst String &String &String &String & operatoroperatoroperatoroperator+=(+=(+=(+=( constconstconstconst String & );String & );String & );String & );
2006 Pearson Education, Inc. All rights reserved.
};};};}; y += zy += zy += zy += z becomes y.y.y.y.operatoroperatoroperatoroperator+=( z )+=( z )+=( z )+=( z )
If global function, needs two arguments
constconstconstconst String &String &String &String &operatoroperatoroperatoroperator+=( String &,+=( String &,+=( String &,+=( String &, constconstconstconst StringStringStringString
& );& );& );& );
y += zy += zy += zy += z becomes operatoroperatoroperatoroperator+=( y, z )+=( y, z )+=( y, z )+=( y, z )
36
8/2/2019 Com 102 Lecture 5
36/111
22.8 Case Study: ArrayArrayArrayArray Class
Pointer-based arrays in C++
No range checking
Cannot be compared meaningfully with ======== No array assignment (array names are constconstconstconst pointers)
If array passed to a function, size must be passed as a separate
2006 Pearson Education, Inc. All rights reserved.
Example: Implement an ArrayArrayArrayArray class with
Range checking
Array assignment
Arrays that know their own size Outputting/inputting entire arrays with >
Array comparisons with ======== and !=!=!=!=
37
8/2/2019 Com 102 Lecture 5
37/111
22.8 Case Study: ArrayArrayArrayArray Class (Cont.)
Copy constructor
Used whenever copy of object is needed:
Passing by value (return value or parameter)
Initializing an object with a copy of another of same type
Array newArray( oldArray );Array newArray( oldArray );Array newArray( oldArray );Array newArray( oldArray ); or
2006 Pearson Education, Inc. All rights reserved.
Array newArray = oldArrayArray newArray = oldArrayArray newArray = oldArrayArray newArray = oldArray (both are identical)
newArraynewArraynewArraynewArray is a copy ofoldArrayoldArrayoldArrayoldArray
Prototype for class ArrayArrayArrayArray
Array( const Array & );Array( const Array & );Array( const Array & );Array( const Array & );
Must take reference
Otherwise, the argument will be passed by value
Which tries to make copy by calling copy constructor
Infinite loop
8/2/2019 Com 102 Lecture 5
38/111
3928
29 // subscript operator for non// subscript operator for non// subscript operator for non// subscript operator for non----const objects returns modifiable lvalueconst objects returns modifiable lvalueconst objects returns modifiable lvalueconst objects returns modifiable lvalue Outline
8/2/2019 Com 102 Lecture 5
39/111
29 // subscript operator for non// subscript operator for non// subscript operator for non// subscript operator for non const objects returns modifiable lvalueconst objects returns modifiable lvalueconst objects returns modifiable lvalueconst objects returns modifiable lvalue
30 intintintint &&&&operatoroperatoroperatoroperator[]([]([]([]( intintintint ););););
31
32 // subscript operator for const objects returns rvalue// subscript operator for const objects returns rvalue// subscript operator for const objects returns rvalue// subscript operator for const objects returns rvalue
33 intintintintoperatoroperatoroperatoroperator[]([]([]([]( intintintint )))) constconstconstconst;;;;
34 privateprivateprivateprivate::::
35 intintintint size;size;size;size; // pointer// pointer// pointer// pointer----based array sizebased array sizebased array sizebased array size
36 intintintint *ptr;*ptr;*ptr;*ptr; // pointer to first element of pointer// pointer to first element of pointer// pointer to first element of pointer// pointer to first element of pointer----based arraybased arraybased arraybased array
37 };};};}; // end class Array// end class Array// end class Array// end class Array
3839 #endif#endif#endif#endif
Outline
Array.hArray.hArray.hArray.h
(2 of 2)Operators for accessing specificelements ofArray object
2006 Pearson Education,Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
40/111
8/2/2019 Com 102 Lecture 5
41/111
8/2/2019 Com 102 Lecture 5
42/111
8/2/2019 Com 102 Lecture 5
43/111
8/2/2019 Com 102 Lecture 5
44/111
45125
126// overloaded output operator for class Array// overloaded output operator for class Array// overloaded output operator for class Array// overloaded output operator for class Array Outline
8/2/2019 Com 102 Lecture 5
45/111
127ostream &ostream &ostream &ostream &operatoroperatoroperatoroperator
8/2/2019 Com 102 Lecture 5
46/111
8/2/2019 Com 102 Lecture 5
47/111
8/2/2019 Com 102 Lecture 5
48/111
8/2/2019 Com 102 Lecture 5
49/111
8/2/2019 Com 102 Lecture 5
50/111
51
8/2/2019 Com 102 Lecture 5
51/111
Software Engineering Observation 22.4
The argument to a copy constructor should bea constconstconstconst reference to allow a constconstconstconst object tobe copied.
2006 Pearson Education, Inc. All rights reserved.
52
8/2/2019 Com 102 Lecture 5
52/111
Common Programming Error 22.6
Note that a copy constructormust receive itsargument by reference, not by value. Otherwise,the copy constructor call results in infiniterecursion (a fatal logic error) because receiving
2006 Pearson Education, Inc. All rights reserved.
to make a copy of the argument object. Recallthat any time a copy of an object is required, theclasss copy constructor is called. If the copyconstructor received its argument by value, the
copy constructor would call itself recursively tomake a copy of its argument!
53
8/2/2019 Com 102 Lecture 5
53/111
Common Programming Error 22.7
If the copy constructor simply copied thepointer in the source object to the targetobjects pointer, then both objects would pointto the same dynamically allocated memory. The
2006 Pearson Education, Inc. All rights reserved.
dynamically allocated memory, and the otherobjects ptrptrptrptr would be undefined, a situationcalled a dangling pointerthis would likelyresult in a serious run-time error (such as earlyprogram termination) when the pointer wasused.
54
8/2/2019 Com 102 Lecture 5
54/111
Software Engineering Observation 22.5
A copy constructor, a destructor and anoverloaded assignment operator are usuallyprovided as a group for any class that uses
2006 Pearson Education, Inc. All rights reserved.
.
55
8/2/2019 Com 102 Lecture 5
55/111
Common Programming Error 22.8
Not providing an overloaded assignment operatorand a copy constructor for a class when objects ofthat class contain pointers to dynamically
2006 Pearson Education, Inc. All rights reserved.
.
56
8/2/2019 Com 102 Lecture 5
56/111
Software Engineering Observation 22.6
It is possible to prevent one object of a classfrom being assigned to another. This is doneby declaring the assignment operator as a
2006 Pearson Education, Inc. All rights reserved.
.
57
8/2/2019 Com 102 Lecture 5
57/111
Software Engineering Observation 22.7
It is possible to prevent class objects frombeing copied; to do this, simply make both theoverloaded assignment operator and the copy
2006 Pearson Education, Inc. All rights reserved.
.
58
22 9 Converting between Types
8/2/2019 Com 102 Lecture 5
58/111
22.9 Converting between Types
Casting
Traditionally, cast integers to floats, etc.
May need to convert between user-defined types
Cast operator (conversion operator)
2006 Pearson Education, Inc. All rights reserved.
onver rom
One class to another
A Class to a built-in type (intintintint, charcharcharchar, etc.)
Must be non-staticstaticstaticstatic member function
Do not specify return type Implicitly returns type to which you are converting
59
22.9 Converting between Types (Cont.)
8/2/2019 Com 102 Lecture 5
59/111
22.9 Converting between Types (Cont.)
Cast operator (conversion operator) (Cont.)
Example
PrototypeA::A::A::A::operator charoperator charoperator charoperator char *()*()*()*() constconstconstconst;;;;
Casts class AAAA to a temporary char *char *char *char *
2006 Pearson Education, Inc. All rights reserved.
static_cast< char * >( s )static_cast< char * >( s )static_cast< char * >( s )static_cast< char * >( s ) callss.operator char *()s.operator char *()s.operator char *()s.operator char *()
Also
A::A::A::A::operator intoperator intoperator intoperator int()()()() constconstconstconst;;;;
A::A::A::A::operatoroperatoroperatoroperator OtherClass()OtherClass()OtherClass()OtherClass() constconstconstconst;;;;
60
22.9 Converting between Types (Cont.)
8/2/2019 Com 102 Lecture 5
60/111
22.9 Converting between Types (Cont.)
Casting can prevent need for overloading
Suppose class StringStringStringString can be cast to char *char *char *char *
cout
8/2/2019 Com 102 Lecture 5
61/111
22.10 Case Study: StringStringStringString Class
Build class StringStringStringString
String creation, manipulation
Similar to class stringstringstringstring in standard library (Chapter 18)
Conversion constructor
Any single-argument constructor
2006 Pearson Education, Inc. All rights reserved.
Example String s1(String s1(String s1(String s1( """"happyhappyhappyhappy"""" ););););
Creates a StringStringStringString from a char *char *char *char *
Overloading function call operator
Powerful (functions can take arbitrarily long and complexparameter lists)
8/2/2019 Com 102 Lecture 5
62/111
8/2/2019 Com 102 Lecture 5
63/111
6449
50 charcharcharchar &&&&operatoroperatoroperatoroperator[]([]([]([]( intintintint );););); // subscript operator (modifiable lvalue)// subscript operator (modifiable lvalue)// subscript operator (modifiable lvalue)// subscript operator (modifiable lvalue)
51 charcharcharcharoperatoroperatoroperatoroperator[]([]([]([]( intintintint )))) constconstconstconst;;;; // subscript operator (rvalue)// subscript operator (rvalue)// subscript operator (rvalue)// subscript operator (rvalue)
52 StringStringStringString operatoroperatoroperatoroperator()(()(()(()( intintintint,,,, intintintint ==== 0000 ) const;) const;) const;) const; // return a substring// return a substring// return a substring// return a substring
Outline
Two overloaded subscriptoperators, for const and
8/2/2019 Com 102 Lecture 5
64/111
gSt gSt gg pope toope top ()(()(()(()( tt,,,, tt 00 ) ;) co st;) co st;) ; // g// etu subst g// etu subst g// g
53 intintintint getLength()getLength()getLength()getLength() cocococonstnstnstnst;;;; // return string length// return string length// return string length// return string length
54 privateprivateprivateprivate::::
55 intintintint length;length;length;length; // string length (not counting null terminator)// string length (not counting null terminator)// string length (not counting null terminator)// string length (not counting null terminator)
56 charcharcharchar *sPtr;*sPtr;*sPtr;*sPtr; // pointer to start of pointer// pointer to start of pointer// pointer to start of pointer// pointer to start of pointer----based stringbased stringbased stringbased string
57
58 voidvoidvoidvoid setString(setString(setString(setString( const charconst charconst charconst char * );* );* );* ); // utility function// utility function// utility function// utility function
59 };};};}; // end class String// end class String// end class String// end class String
60
61 #endif#endif#endif#endif
String.hString.hString.hString.h
(3 of 3)
non-const objects
Overload the function calloperator () to return a substring
2006 Pearson Education,Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
65/111
8/2/2019 Com 102 Lecture 5
66/111
8/2/2019 Com 102 Lecture 5
67/111
8/2/2019 Com 102 Lecture 5
68/111
8/2/2019 Com 102 Lecture 5
69/111
8/2/2019 Com 102 Lecture 5
70/111
71
Outline175
176// overloaded input operator// overloaded input operator// overloaded input operator// overloaded input operator
177istream &operator>>( istream &input, String &s )istream &operator>>( istream &input, String &s )istream &operator>>( istream &input, String &s )istream &operator>>( istream &input, String &s )
178{{{{
179 hhhh [[[[ 100100100100 ]]]] // b ff i// b ff i// b ff i// b ff i
8/2/2019 Com 102 Lecture 5
71/111
String.cppString.cppString.cppString.cpp
(7 of 7)
179 charcharcharchar temp[temp[temp[temp[ 100100100100 ];];];]; // buffer to store input// buffer to store input// buffer to store input// buffer to store input
180 input >> setw(input >> setw(input >> setw(input >> setw( 100100100100 ) >> temp;) >> temp;) >> temp;) >> temp;
181 s = temp;s = temp;s = temp;s = temp; // use String class assignment operator// use String class assignment operator// use String class assignment operator// use String class assignment operator
182 returnreturnreturnreturn input;input;input;input; // enables cascading// enables cascading// enables cascading// enables cascading
183}}}} // end function operator>>// end function operator>>// end function operator>>// end function operator>>
2006 Pearson Education,Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
72/111
8/2/2019 Com 102 Lecture 5
73/111
8/2/2019 Com 102 Lecture 5
74/111
8/2/2019 Com 102 Lecture 5
75/111
8/2/2019 Com 102 Lecture 5
76/111
77
8/2/2019 Com 102 Lecture 5
77/111
Software Engineering Observation 22.8
When a conversion constructor is used to perform
an implicit conversion, C++ can apply only oneimplicit constructor call (i.e., a single user-defined
2006 Pearson Education, Inc. All rights reserved.
overloaded operator. The compiler will not matchan overloaded operators needs by performing aseries of implicit, user-defined conversions.
78
8/2/2019 Com 102 Lecture 5
78/111
Performance Tip 22.2
Overloading the +=+=+=+= concatenation operator with
an additional version that takes a single argumentof type const charconst charconst charconst char * executes more efficientlythan having only a version that takes a StringStringStringString
2006 Pearson Education, Inc. All rights reserved.
argument. Without the const c arconst c arconst c arconst c ar version of
the +=+=+=+= operator, a const charconst charconst charconst char * argumentwould first be converted to a StringStringStringString object withclass StringStringStringStrings conversion constructor, then the
+=+=+=+= operator that receives a StringStringStringString argumentwould be called to perform the concatenation.
79
8/2/2019 Com 102 Lecture 5
79/111
Software Engineering Observation 22.9
Using implicit conversions with overloaded
operators, rather than overloading operatorsfor many different operand types, often
2006 Pearson Education, Inc. All rights reserved.
,
to modify, maintain and debug.
80
8/2/2019 Com 102 Lecture 5
80/111
Software Engineering Observation 22.10
By implementing member functions using
previously defined member functions, theprogrammer reuses code to reduce the amount
2006 Pearson Education, Inc. All rights reserved.
.
81
8/2/2019 Com 102 Lecture 5
81/111
Error-Prevention Tip 22.2
Returning a nonnonnonnon----constconstconstconst char reference from anoverloaded subscript operator in a StringStringStringString classis dangerous. For example, the client could use
'''' ''''
2006 Pearson Education, Inc. All rights reserved.
in the string.
82
22.11 Overloading ++++++++ and --------
8/2/2019 Com 102 Lecture 5
82/111
Increment/decrement operators can be
overloaded
Suppose we want to add 1 to a DateDateDateDate object, d1d1d1d1 Prototype (member function)
Date &Date &Date &Date &o eratoro eratoro eratoro erator++++++++
2006 Pearson Education, Inc. All rights reserved.
++d1++d1++d1++d1 becomes d1.d1.d1.d1.operatoroperatoroperatoroperator++()++()++()++()
Prototype (global function)
Date &Date &Date &Date &operatoroperatoroperatoroperator++( Date & );++( Date & );++( Date & );++( Date & );
++d1++d1++d1++d1 becomes operatoroperatoroperatoroperator++( d1 )++( d1 )++( d1 )++( d1 )
83
22.11 Overloading ++++++++ and -------- (Cont.)
8/2/2019 Com 102 Lecture 5
83/111
To distinguish prefix and postfix increment
Postfix increment has a dummy parameter
An intintintint with value 0000 Prototype (member function)
DateDateDateDate operatoroperatoroperatoroperator++(++(++(++( intintintint ););););
2006 Pearson Education, Inc. All rights reserved.
d1++d1++d1++d1++ becomes d1.d1.d1.d1.operatoroperatoroperatoroperator++(++(++(++( 0000 ))))
Prototype (global function)
DateDateDateDate operatoroperatoroperatoroperator++( Date &,++( Date &,++( Date &,++( Date &, intintintint ););););
d1++d1++d1++d1++ becomes operatoroperatoroperatoroperator++( d1,++( d1,++( d1,++( d1, 0000 ))))
84
22.11 Overloading ++++++++ and -------- (Cont.)
8/2/2019 Com 102 Lecture 5
84/111
Return values
Prefix increment
Returns by reference (Date &Date &Date &Date &) lvalue (can be assigned)
Postfix increment
2006 Pearson Education, Inc. All rights reserved.
Returns by value
Returns temporary object with old value
rvalue (cannot be on left side of assignment)
All this applies to decrement operators as well
85
8/2/2019 Com 102 Lecture 5
85/111
Performance Tip 22.3
The extra object that is created by the postfix
increment (or decrement) operator can result in asignificant performance problemespecially when
2006 Pearson Education, Inc. All rights reserved.
. ,
should use the postfix increment (or decrement)operator only when the logic of the programrequires postincrementing (or postdecrementing).
86
22.12 Case Study: A DateDateDateDate Class
8/2/2019 Com 102 Lecture 5
86/111
Example DateDateDateDate class
Overloaded increment operator
Change day, month and year Overloaded +=+=+=+= operator
Function to test for lea ears
2006 Pearson Education, Inc. All rights reserved.
Function to determine if day is last of month
8/2/2019 Com 102 Lecture 5
87/111
8/2/2019 Com 102 Lecture 5
88/111
8/2/2019 Com 102 Lecture 5
89/111
8/2/2019 Com 102 Lecture 5
90/111
8/2/2019 Com 102 Lecture 5
91/111
8/2/2019 Com 102 Lecture 5
92/111
8/2/2019 Com 102 Lecture 5
93/111
94
22.13 Standard Library Class stringstringstringstring
8/2/2019 Com 102 Lecture 5
94/111
Class built into C++
Available for anyone to use
Class stringstringstringstring Similar to our StringStringStringString class
2006 Pearson Education, Inc. All rights reserved.
95
22.13 Standard Library Class stringstringstringstring(Cont.)
8/2/2019 Com 102 Lecture 5
95/111
Class stringstringstringstring
Header , namespace stdstdstdstd
Can initialize string s1( "hi" );string s1( "hi" );string s1( "hi" );string s1( "hi" ); Overloaded
8/2/2019 Com 102 Lecture 5
96/111
Class stringstringstringstring (Cont.)
Substring member function substrsubstrsubstrsubstr s1.substr( 0, 14 );s1.substr( 0, 14 );s1.substr( 0, 14 );s1.substr( 0, 14 );
Starts at location 0, gets 14 characters s1.substr( 15 );s1.substr( 15 );s1.substr( 15 );s1.substr( 15 );
Substring beginning at location 15, to the end
2006 Pearson Education, Inc. All rights reserved.
Overloaded [][][][] Access one character
No range checking (if subscript invalid)
Member function atatatat Accesses one character
ExampleExampleExampleExample
s1.at( 10 );s1.at( 10 );s1.at( 10 );s1.at( 10 );
Has bounds checking, throws an exception if subscript is invalid
Will end program (learn more in Chapter 16)
8/2/2019 Com 102 Lecture 5
97/111
8/2/2019 Com 102 Lecture 5
98/111
8/2/2019 Com 102 Lecture 5
99/111
8/2/2019 Com 102 Lecture 5
100/111
101
22.14 explicitexplicitexplicitexplicit Constructors
I li it i
8/2/2019 Com 102 Lecture 5
101/111
Implicit conversions
Performed by compiler using single-argument constructors
Sometimes, implicit conversions are undesirable or error-prone
Keyword explicitexplicitexplicitexplicit
2006 Pearson Education, Inc. All rights reserved.
Suppresses implicit conversions via conversion
constructors
102
Common Programming Error 22.9
8/2/2019 Com 102 Lecture 5
102/111
Common Programming Error 22.9
Unfortunately, the compiler might use implicit
conversions in cases that you do not expect,resulting in ambiguous expressions that generate
2006 Pearson Education, Inc. All rights reserved.
-
logic errors.
1031 // Fig.// Fig.// Fig.// Fig. 22222222.16: Fig.16: Fig.16: Fig.16: Fig22222222_16.cpp_16.cpp_16.cpp_16.cpp
2 // Driver for simple class Array.// Driver for simple class Array.// Driver for simple class Array.// Driver for simple class Array.
3 #include#include#include#include
4 usingusingusingusing std::cout;std::cout;std::cout;std::cout;
5 usingusingusingusing std::endl;std::endl;std::endl;std::endl;
6
7 #include#include#include#include"Array.h""Array.h""Array.h""Array.h"
Outline
fig22_16.cppfig22_16.cppfig22_16.cppfig22_16.cpp
8/2/2019 Com 102 Lecture 5
103/111
8
9 voidvoidvoidvoid outputArray(outputArray(outputArray(outputArray( constconstconstconst Array & );Array & );Array & );Array & ); // prototype// prototype// prototype// prototype
10
11 intintintint main()main()main()main()
12 {{{{13 Array integers1(Array integers1(Array integers1(Array integers1( 7777 );););); // 7// 7// 7// 7----element arrayelement arrayelement arrayelement array
14 outputArray( integers1 );outputArray( integers1 );outputArray( integers1 );outputArray( integers1 ); // output Array integers1// output Array integers1// output Array integers1// output Array integers1
15 outputArray( 3 ); // convert 3 to an Array and output Arrays contentsoutputArray( 3 ); // convert 3 to an Array and output Arrays contentsoutputArray( 3 ); // convert 3 to an Array and output Arrays contentsoutputArray( 3 ); // convert 3 to an Array and output Arrays contents
(1 of 2)
2006 Pearson Education,
Inc. All rights reserved.
16 returnreturnreturnreturn0000;;;;
17 }}}} // end main// end main// end main// end main
Would logically want
this to generate an error
10418
19 // print Array contents// print Array contents// print Array contents// print Array contents
20 voidvoidvoidvoid outputArray(outputArray(outputArray(outputArray( constconstconstconst Array &arrayToOutput )Array &arrayToOutput )Array &arrayToOutput )Array &arrayToOutput )
21 {{{{
22 cout
8/2/2019 Com 102 Lecture 5
104/111
The Array received has 7 elements. The contents are:The Array received has 7 elements. The contents are:The Array received has 7 elements. The contents are:The Array received has 7 elements. The contents are:
0 0 0 00 0 0 00 0 0 00 0 0 00 0 00 0 00 0 00 0 0
The Array received has 3 elements. The contents are:The Array received has 3 elements. The contents are:The Array received has 3 elements. The contents are:The Array received has 3 elements. The contents are:
0 0 00 0 00 0 00 0 0
(2 of 2)
2006 Pearson Education,
Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
105/111
8/2/2019 Com 102 Lecture 5
106/111
107
Common Programming Error 22.10
8/2/2019 Com 102 Lecture 5
107/111
g g
Attempting to invoke an explicitexplicitexplicitexplicit constructor
for an implicit conversion is a compilation error.
2006 Pearson Education, Inc. All rights reserved.
8/2/2019 Com 102 Lecture 5
108/111
1091 // Fig.// Fig.// Fig.// Fig. 22222222.18: Fig.18: Fig.18: Fig.18: Fig22222222_18.cpp_18.cpp_18.cpp_18.cpp
2 // Driver for simple class Array.// Driver for simple class Array.// Driver for simple class Array.// Driver for simple class Array.
3 #include#include#include#include
4 usingusingusingusing std::cout;std::cout;std::cout;std::cout;
5 usingusingusingusing std::endl;std::endl;std::endl;std::endl;
6
7 #include#include#include#include"Array.h""Array.h""Array.h""Array.h"
8
Outline
Fig22_18.cppFig22_18.cppFig22_18.cppFig22_18.cpp
(1 of 2)
Using keyword explicit on the
8/2/2019 Com 102 Lecture 5
109/111
8
9 voidvoidvoidvoid outputArray(outputArray(outputArray(outputArray( constconstconstconst Array & );Array & );Array & );Array & ); // prototype// prototype// prototype// prototype
10
11 intintintint main()main()main()main()
12 {{{{13 Array integers1(Array integers1(Array integers1(Array integers1( 7777 );););); // 7// 7// 7// 7----element arrayelement arrayelement arrayelement array
14 outputArray( integers1 );outputArray( integers1 );outputArray( integers1 );outputArray( integers1 ); // output Array integers1// output Array integers1// output Array integers1// output Array integers1
15 outputArray( 3 ); // convert 3 to an Array and output Arrays contentsoutputArray( 3 ); // convert 3 to an Array and output Arrays contentsoutputArray( 3 ); // convert 3 to an Array and output Arrays contentsoutputArray( 3 ); // convert 3 to an Array and output Arrays contents
(1 of 2)Using keyword explicit on the
conversion constructor disallows this line to
erroneously call the conversion constructor
2006 Pearson Education,
Inc. All rights reserved.
16 outputArray( Array(outputArray( Array(outputArray( Array(outputArray( Array( 3333 ) );) );) );) ); // explicit single// explicit single// explicit single// explicit single----argument constructorargument constructorargument constructorargument constructor callcallcallcall
17 returnreturnreturnreturn0000;;;;
18 }}}} // end main// end main// end main// end main
An explicit call to the conversion
constructor is still allowed
11019
20 // print array contents// print array contents// print array contents// print array contents
21 voidvoidvoidvoid outputArray(outputArray(outputArray(outputArray( constconstconstconst Array &arrayToOutput )Array &arrayToOutput )Array &arrayToOutput )Array &arrayToOutput )
22 {{{{
23 cout
8/2/2019 Com 102 Lecture 5
110/111
c:c:c:c:\\\\examplesexamplesexamplesexamples\\\\chchchch22222222\\\\FigFigFigFig22222222_17_18_17_18_17_18_17_18\\\\FigFigFigFig22222222_18.cpp(15) : error C2664:_18.cpp(15) : error C2664:_18.cpp(15) : error C2664:_18.cpp(15) : error C2664:'outputArray' : cannot convert parameter 1 from 'int' to 'const Array &''outputArray' : cannot convert parameter 1 from 'int' to 'const Array &''outputArray' : cannot convert parameter 1 from 'int' to 'const Array &''outputArray' : cannot convert parameter 1 from 'int' to 'const Array &'
Reason: cannot convert from 'int' to 'const Array'Reason: cannot convert from 'int' to 'const Array'Reason: cannot convert from 'int' to 'const Array'Reason: cannot convert from 'int' to 'const Array'
Constructor for class 'Array' is deConstructor for class 'Array' is deConstructor for class 'Array' is deConstructor for class 'Array' is declared 'explicit'clared 'explicit'clared 'explicit'clared 'explicit'
(2 of 2)
2006 Pearson Education,
Inc. All rights reserved.
111
Error-Prevention Tip 22.3
8/2/2019 Com 102 Lecture 5
111/111
Use the explicitexplicitexplicitexplicit keyword on single-argument
constructors that should not be used by thecompiler to perform implicit conversions.
2006 Pearson Education, Inc. All rights reserved.
Top Related