Title: Classes and Data Abstraction
1Classes and Data Abstraction
2Objects
- 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
3Methods
- 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
4Methods 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?
5Invoking 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
6Strings
- string Class part of the standard template
library - stores multiple characters
- Examples
- string name
- string flower
- To create objects called class instantiation
- ClassName variableName(arguments)
- string flower(tulip)
7Assigning value later
- Long version
- string flower
- string name
- flower string(Rose)
- name string(Pete)
- Shorter version
- flower Rose
- name Pete
Special assignment for strings
8Creating examples
- Assume char buffer hi
- string s0(string)
- string s1
- string s2(s0)
- string s3(buffer)
- string s4(buffer, 1)
- string s5(5, f)
9String Concatenation
- Use the plus operator to join Strings together
- is the concatenation operator
- Example
- string fullName name flower
fullName holds the value Pete Rose
10String 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
11More 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
stringnpos - str.find(i, 5) Determines the position of the
first occurrence of i in str starting the
search at position 5
12String Methods Examples
- string saying(C is fun!)
- saying.length()
- What is the result?
-
- saying.at(0)
- What is the result?
-
- saying.at(saying.length() 1)
- What is the result?
-
13String Methods Examples
saying C is fun!
- saying.substr(5, saying.length())
- What is the result?
-
- saying.substring(0, 3)
- What is the result?
-
- saying.find(C)
- What is the result?
-
- saying.find(c)
- What is the result?
-
14Displaying 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 ltlt The first blank is a position
- ltlt saying.find( ))
15Object-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
166.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
17Developing a Worker Class
- The class definition
- Data field declarations
- Constructor definitions
- Method definitions
18Library 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
19Data 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
20Library Book Declaration
title author date due who checked the book out
- class LibraryBook
-
- private
-
- public
-
21Constructor 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
22Library Book adding the constructor
- class LibraryBook
-
- private
- string title
- string author
- string borrower
- MyDate dueDate
-
- public
- // Construtor
-
-
23Method 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)
24Library Book Adding the Methods
- class LibraryBook
- private
- string title
- string author
- string borrower
- MyDate dueDate
-
- public
- // Construtor
- LibraryBook(string t, String a)
-
- // Return title
-
- // Returns dueDate
-
-
- // Checks out book
-
get title get due date check out check in
Found in the file LibraryBook.h
25Calling 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()
26Postconditions
- 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
276.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
286.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 ()
- ClassNameclassVariableName
- Variables only known to function they are defined
in - Variables are destroyed after function completion
29Library Book Method definitionsConstructor
- Form classNamemethodName(parameters)
- Purpose is to initialize the data fields
- LibraryBookLibraryBook(string t, string a)
-
-
30Writing code for Library Book Methods
- string LibraryBookgetTitle()
-
- return title
-
- Date LibraryBookgetDueDate()
-
- return dueDate
-
- void LibraryBookcheckout(string name, MyDate
due) -
- borrower name
- dueDate due
-
- void LibraryBookcheckin()
-
- borrower
- dueDate MyDate()
-
Found in the file LibraryBook.cpp
31Ways to Create Strings
string 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
32Access to string Elements
c si 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()
33string 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
34string Search and Substrings
s.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
35string Comparisons
s1 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 lt s2 Returns true if s1 comes before s2 lexicographically, else returns false
s1 gt s2 Returns true if s1 comes after s2 lexicographically, else returns false
s1 lt s2 Same as !(s1 gt s2)
S1 gt s2 Same as !(s1 lt s2)
Lexicographic ordering compares characters at
corresponding positions sequentially until a
position i is found where s1i ? s2i. Then
the expression s1 lt s2 has the same Boolean
value as s1i lt s2i.
36string I/O Operations
os ltlt str Places the characters from string str onto stream os
is gtgt 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/stri
ng.htm
37fig08_13.cpp(1 of 4)
- 1 // Fig. 8.13 fig08_13.cpp
- 2 // Standard library string class test
program. - 3 include ltiostreamgt
- 4 using stdcout
- 5 using stdendl
- 6 include ltstringgt
- 7 using stdstring
- 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 ltlt "s1 is \"" ltlt s1 ltlt "\" s2 is
\"" ltlt s2 - 16 ltlt "\" s3 is \"" ltlt s3 ltlt '\"'
- 17 ltlt "\n\nThe results of comparing s2
and s1" - 18 ltlt "\ns2 s1 yields "
- 19 ltlt ( s2 s1 ? "true" "false" )
38fig08_13.cpp(2 of 4)
- 21 ltlt "\ns2 gt s1 yields "
- 22 ltlt ( s2 gt s1 ? "true" "false" )
- 23 ltlt "\ns2 lt s1 yields "
- 24 ltlt ( s2 lt s1 ? "true" "false" )
- 25 ltlt "\ns2 gt s1 yields "
- 26 ltlt ( s2 gt s1 ? "true" "false" )
- 27 ltlt "\ns2 lt s1 yields "
- 28 ltlt ( s2 lt s1 ? "true" "false" )
- 29
- 30 // test string member function empty
- 31 cout ltlt "\n\nTesting s3.empty()\n"
- 32 if ( s3.empty() )
- 33 cout ltlt "s3 is empty assigning s1 to
s3\n" - 34 s3 s1 // assign s1 to s3
- 35 cout ltlt "s3 is \"" ltlt s3 ltlt "\""
- 36
- 37
- 38 // test overloaded string concatenation
operator - 39 cout ltlt "\n\ns1 s2 yields s1 "
39fig08_13.cpp(3 of 4)
- 42 // test overloaded string concatenation
operator - 43 // with C-style string
- 44 cout ltlt "\n\ns1 \" to you\"
yields\n" - 45 s1 " to you"
- 46 cout ltlt "s1 " ltlt s1 ltlt "\n\n"
- 47
- 48 // test string member function substr
- 49 cout ltlt "The substring of s1 starting at
location 0 for\n" - 50 ltlt "14 characters, s1.substr(0,
14), is\n" - 51 ltlt s1.substr( 0, 14 ) ltlt "\n\n"
- 52
- 53 // test substr "to-end-of-string" option
- 54 cout ltlt "The substring of s1 starting
at\n" - 55 ltlt "location 15, s1.substr(15),
is\n" - 56 ltlt s1.substr( 15 ) ltlt '\n'
- 57
40fig08_13.cpp(4 of 4)
- 58 // test using subscript operator to
create lvalue - 59 s1 0 'H'
- 60 s1 6 'B'
- 61 cout ltlt "\ns1 after s10 'H' and
s16 'B' is " - 62 ltlt s1 ltlt "\n\n"
- 63
- 64 // test subscript out of range with
string member function "at" - 65 cout ltlt "Attempt to assign 'd' to s1.at(
30 ) yields" ltlt endl - 66 s1.at( 30 ) 'd' // ERROR
subscript out of range - 67
- 68 return 0
- 69
- 70 // end main
41fig08_13.cppoutput (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 gt s1 yields false
- s2 lt s1 yields true
- s2 gt s1 yields false
- s2 lt s1 yields true
-
- Testing s3.empty()
- s3 is empty assigning s1 to s3
- s3 is "happy"
-
- s1 s2 yields s1 happy birthday
-
-
42fig08_13.cppoutput (2 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 s10 'H' and s16 'B' is Happy
Birthday to you - Attempt to assign 'd' to s1.at( 30 ) yields
-
- abnormal program termination