lecture 5: part 2 classes and data abstraction. objects models of things in the real world defined...
TRANSCRIPT
Lecture 5: Part 2
Classes and Data Abstraction
Objects
Models of things in the real world Defined in classes
Class name is the object name Example: Library Book Use methods to interact with objects
Methods
Used for one of the following reasons To change the state of an object – the information
stored in the object To calculate a result To retrieve a particular data item that is stored in
an object To get data from the user To display the result of an operation
Methods for a Library Book
Data associated with a library book Whether it is checked out Who has checked it out When it is due Title of the book
What should the methods be?
Invoking methods
Create instance of class LibraryBook book1;
To call a method, use the dot notation objectName.methodName(argumentlist)
book1.setTitle(“The Da Vinci Code”); Member access operators
Dot operator (.) for class members
Strings
string Class – part of the standard template library stores multiple characters
Examples string name; string flower;
To create objects – called class instantiationClassName variableName(arguments); string flower(“tulip”);
Assigning value later
Long versionstring flower;
string name;
flower = string(“Rose”);
name = string(“Pete”); Shorter versionflower = “Rose”;
name = “Pete”;
Special assignment for
strings
Creating examples
Assume: char buffer[] = “hi”; string s0(“string”); string s1; string s2(s0); string s3(buffer); string s4(buffer, 1); string s5(5, ‘f’);
string
Ø
string
hi
h
fffff
String Concatenation
Use the plus operator to join Strings together ‘+’ is the concatenation operator Example:
string fullName = name + “ “ + flower;
fullName holds the value “Pete
Rose”
String Methods
str.length() – Finds the length of the string (str.size() does the same thing)
str.at(6) – Gets the character at position 6 (the first character is at position 0)
str.subString(5) – Gets the part of str starting a position 5
str.substr (5, 2) – Gets the 2 characters of str starting at position 5
More String Methods
str.find(“is”) – Determines the position of the first occurrence of “is” in str. If the “is” does not occur in the string, returns string::npos
str.find(“i”, 5) – Determines the position of the first occurrence of “i” in str starting the search at position 5
String Methods Examples
string saying(“C++ is fun!”);
saying.length(); What is the result?
the integer 11
saying.at(0); What is the result?
the letter C
saying.at(saying.length() – 1); What is the result?
the character !
String Methods Examples
saying.substr(5, saying.length()); What is the result?
The string “is fun!”saying.substring(0, 3); What is the result?
The string “C++”saying.find(“C++”); What is the result?
The integer 0saying.find(“c++”); What is the result?
The integer string::npos
saying = “C++ is fun!”
Displaying and Storing Method Results Use assignment statements to store the result of a
method call int posBlank = saying.find(“ “);
posBlank stores the value 3 String firstWord = saying.substr(0, posBlank);
firstWord store the value “C++”
Including the method call in the output statement cout << “The first blank is a position “
<< saying.find(“ “));
Object-Oriented Design
Program divided into 2 parts Application
File that contains main Create and manipulate one or more worker objects
Worker classes Contain methods that perform different kinds of
operations Example: string
6.1 Introduction
Object-oriented programming (OOP) Encapsulates data (attributes) and functions (behavior) into
packages called classes Information hiding
Class objects communicate across well-defined interfaces Implementation details hidden within classes themselves
User-defined (programmer-defined) types: classes Data (data members) Functions (member functions or methods) Similar to blueprints – reusable Class instance: object
Developing a Worker Class
The class definition Data field declarations Constructor definitions Method definitions
Library Book Example
Data Fields title author date due who checked the book
out
Methods get title get author get due date get lendee calculate overdue fine calculate days until due check out renew check in
Data Fields Store the information associated with an object of that
class May be referenced by any method in the class Values of the fields represent the state of the object Also called instance or class variables Data field declaration
typeName dataFieldName; Examples
int pennies; string month;
Library Book Declaration
class LibraryBook {private:
string title; string author; MyDate dueDate; string borrower;
public:};
titleauthordate duewho checked the book out
Constructor Definitions
Method that is called when a new object is created
Purpose is to initialize the data fields May be multiple constructors with different
sets of arguments
Library Book – adding the constructorclass LibraryBook {
private: string title; string author; string borrower; MyDate dueDate;
public: // Construtor LibraryBook(string t, String a);};
Method Declarations
Method prototype species the name of the method data type of the value returned parameters in parentheses Form
resultType methodName([parameter list]) Example:
double getPrice(); void setPrice(double);
Library Book – Adding the Methodsclass LibraryBook { private: string title; string author; string borrower; MyDate dueDate; public: // Construtor LibraryBook(string t, String a); // Return title string getTitle();
// Returns dueDate MyDate getDueDate(); // Checks out book void checkout(string name, MyDate due);
// Checks book in void checkin();};
get titleset due datecheck outcheck in
Found in the file: LibraryBook.h
Calling Methods
A call to a method is considered a statement For methods return void
Example: book1.checkin(); For methods returning a value (non-void), you
should store the value in a variable or use the value Example: string out = “Title – “ + book1.getTitle();
Postconditions
Comments that precede a method Tell user of the class what will be true after the
method is called Part of the documentation Examples
Method returns the title of the book // postcondition: returns the title of this book
Method checks in a book // postcondition: sets borrower to empty string and
dueDate to default value
6.6 Class Scope and Accessing Class Members Class scope
Data members, member functions Within class scope
Class members Immediately accessible by all member functions Referenced by name
Outside class scope Referenced through handles
Object name, reference to object, pointer to object
File scope Nonmember functions
6.6 Class Scope and Accessing Class Members Function scope
Variables declared in member function Only known to function Variables with same name as class-scope
variables Class-scope variable “hidden”
Access with scope resolution operator (::)
ClassName::classVariableName
Variables only known to function they are defined in
Variables are destroyed after function completion
Library Book Method definitionsConstructor Form: className::methodName([parameters]) Purpose is to initialize the data fieldsLibraryBook::LibraryBook(string t, string a)
{
title = t;
author = a;
borrower = “"; // book is not currently
// checked out
dueDate = MyDate();
}
Writing code for Library Book Methodsstring LibraryBook::getTitle(){
return title;}Date LibraryBook::getDueDate(){
return dueDate;}void LibraryBook::checkout(string name, MyDate due){
borrower = name;dueDate = due;
}void LibraryBook::checkin(){
borrower = “”;dueDate = MyDate();
}
Found in the file: LibraryBook.cpp
Ways to Create Stringsstring s; Default constructor. Creates an empty string
string s (str); Copy constructor. Creates a new string s as a copy of another string, str
string s(str,
indx);
Creates a new string s from characters starting at index indx of str
string s(str,
indx, count);
Creates a new string s initialized by at most count characters from str, starting at index indx in str
string s(cstr); Creates a new string s initialized with characters from the cstring cstr
string s(charArray,
count);Creates a new string s initialized with at most count characters from char array charArray
string s(count,
ch);
Creates a new string s initialized with count instances of character ch
Access to string Elements
c = s[i] Indexed access with no range checking. Character at index i is returned
c = s.at(i) Indexed access with range checking. Character at index i is returned. Throws an out_of_range excepetion if i ≥ s.size()
string size methods
s.length() Returns the number of characters currently in s
s.size() Same as s.length()
s.resize(newSize, padChar)
Changes the size of s to newSize, filling with repetitions of the character padChar if necessary
s.empty() Returns true if s is empty, else returns false
s.capacity() Returns the number of characters that s can contain without having to reallocate
string Search and Substringss.find(str) Returns the integer index of the first position of the
first occurrence of string str in s
s.find(str,
pos)
Returns the integer index of the first position of the first occurrence of string str in s, with the search starting at position pos of s
s.find_first_of
(delim, pos)
Returns the integer index of the first position of the first occurrence of any character from the string delim, with the search starting at position pos of s
s.find_first_not_of(delim, pos)
Returns the integer index of the first position of the first occurrence of any character not in the string delim, with the search starting at position pos of s
s.substr(pos, len)
Returns a string object that represents a substring of s of at most len characters, starting at position pos of s. If pos is too large, an out_of_range exception is thrown
string Comparisonss1 == s2 Returns true if all characters of s1 and s2 are
pairwise equal, else turns false
s1 != s2 Returns true if not all characters of s1 and s2 are pairwise equal, else returns false
s1 < s2 Returns true if s1 comes before s2 lexicographically, else returns false
s1 > s2 Returns true if s1 comes after s2 lexicographically, else returns false
s1 <= s2 Same as !(s1 > s2)
S1 >= s2 Same as !(s1 < s2)
Lexicographic ordering compares characters at corresponding positions sequentiallyuntil a position i is found where s1[i] ≠ s2[i]. Then the expression s1 < s2 has the same Boolean value as s1[i] < s2[i].
string I/O Operationsos << str Places the characters from string str onto
stream os
is >> str Extracts characters from stream is into string str. Leading whitespace characters are skipped, and input stops at the first trailing whitespace character
getline(is,
str, delimiter)
Reads characters from stream is into string str up to end-of-file or until the character delimiter is extracted. The delimiter is removed from is and discarded. Note: getline is not a member of the string class. It is a stand-alone, global function.
More complete list of class methods: http://www.msoe.edu/eecs/cese/resources/stl/string.htm
fig08_13.cpp(1 of 4)
1 // Fig. 8.13: fig08_13.cpp
2 // Standard library string class test program.
3 #include <iostream> 4 using std::cout;
5 using std::endl; 6 #include <string> 7 using std::string;
8 9 int main() {10 string s1( "happy" );
11 string s2( " birthday" );
12 string s3;
13 14 // test overloaded equality and relational operators
15 cout << "s1 is \"" << s1 << "\"; s2 is \"" << s2
16 << "\"; s3 is \"" << s3 << '\"'
17 << "\n\nThe results of comparing s2 and s1:"
18 << "\ns2 == s1 yields "
19 << ( s2 == s1 ? "true" : "false" )
20 << "\ns2 != s1 yields "
21 << ( s2 != s1 ? "true" : "false" )
fig08_13.cpp(2 of 4)
21 << "\ns2 > s1 yields "
22 << ( s2 > s1 ? "true" : "false" )
23 << "\ns2 < s1 yields "
24 << ( s2 < s1 ? "true" : "false" )
25 << "\ns2 >= s1 yields "
26 << ( s2 >= s1 ? "true" : "false" )
27 << "\ns2 <= s1 yields "
28 << ( s2 <= s1 ? "true" : "false" );
29 30 // test string member function empty
31 cout << "\n\nTesting s3.empty():\n"; 32 if ( s3.empty() ) {
33 cout << "s3 is empty; assigning s1 to s3;\n";
34 s3 = s1; // assign s1 to s3
35 cout << "s3 is \"" << s3 << "\"";
36 }37 38 // test overloaded string concatenation operator
39 cout << "\n\ns1 += s2 yields s1 = ";
40 s1 += s2; // test overloaded concatenation
41 cout << s1;
fig08_13.cpp(3 of 4)
42 // test overloaded string concatenation operator
43 // with C-style string
44 cout << "\n\ns1 += \" to you\" yields\n";
45 s1 += " to you";
46 cout << "s1 = " << s1 << "\n\n";
47 48 // test string member function substr
49 cout << "The substring of s1 starting at location 0 for\n"
50 << "14 characters, s1.substr(0, 14), is:\n"
51 << s1.substr( 0, 14 ) << "\n\n";
52 53 // test substr "to-end-of-string" option
54 cout << "The substring of s1 starting at\n"
55 << "location 15, s1.substr(15), is:\n"
56 << s1.substr( 15 ) << '\n';
57
fig08_13.cpp(4 of 4)
58 // test using subscript operator to create lvalue
59 s1[ 0 ] = 'H';
60 s1[ 6 ] = 'B';
61 cout << "\ns1 after s1[0] = 'H' and s1[6] = 'B' is: "
62 << s1 << "\n\n";
63 64 // test subscript out of range with string member function "at"
65 cout << "Attempt to assign 'd' to s1.at( 30 ) yields:" << endl;
66 s1.at( 30 ) = 'd'; // ERROR: subscript out of range
67 68 return 0;
69 70 } // end main
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;
s3 is "happy"
s1 += s2 yields s1 = happy birthday
fig08_13.cppoutput (1 of 2)
s1 += " to you" yields
s1 = happy birthday to you
The substring of s1 starting at location 0 for
14 characters, s1.substr(0, 14), is:
happy birthday
The substring of s1 starting at
location 15, s1.substr(15), is:
to you
s1 after s1[0] = 'H' and s1[6] = 'B' is: Happy Birthday to you
Attempt to assign 'd' to s1.at( 30 ) yields:
abnormal program termination
fig08_13.cppoutput (2 of 2)
Example
999999
976001
124100
402976
432402
762800
001761
761432
100124
800762
Orig
inal
Arra
y Arra
y Af
ter
2nd P
ass
Arra
y Af
ter
1st P
ass
Arra
y Af
ter
3rd P
ass
Table
[0] [1] [2] [3] … [n-1]
[0] 800 100
[1] 761 001
[2] 762 432 402
[3]
[4] 124
[5]
[6] 976
[7]
[8]
[9] 999
•Insert original array into the table as shown•Collect the values so they are ordered as shown in Array After 1st Pass
Example
999999999
976976001
762124100
761402976
432432402
124762800
402001761
001761432
100100124
800800762
Orig
inal
Arra
y Arra
y Af
ter
2nd P
ass
Arra
y Af
ter
1st P
ass
Arra
y Af
ter
3rd P
ass
Table
[0] [1] [2] [3] … [n-1]
[0] 800 100 001 402
[1]
[2] 124
[3] 432
[4]
[5]
[6] 761 762
[7] 976
[8]
[9] 999
•Doing the same process for the tens place
Example
999999999999
976976976001
800762124100
762761402976
761432432402
432124762800
402402001761
124001761432
100100100124
001800800762
Orig
inal
Arra
y Arra
y Af
ter
2nd P
ass
Arra
y Af
ter
1st P
ass
Arra
y Af
ter
3rd P
ass
Table
[0] [1] [2] [3] … [n-1]
[0] 001
[1] 100 124
[2]
[3]
[4] 402 432
[5]
[6]
[7] 761 762
[8] 800
[9] 976 999
•Doing the same process for the hundreds place