Classes and Data Abstraction Lecture 9 Objects n
Classes and Data Abstraction Lecture 9
Objects n n Models of things in the real world Defined in classes q n n Class name is the object name Example: Library Book Use methods to interact with objects
Methods n Used for one of the following reasons q q q 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 n Data associated with a library book q q n 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 n Create instance of class q n Library. Book book 1; To call a method, use the dot notation q object. Name. method. Name(argumentlist) q book 1. set. Title(“The Da Vinci Code”); Member access operators n Dot operator (. ) for class members
Strings n string Class – part of the standard template library q n Examples q q n stores multiple characters string name; string flower; To create objects – called class instantiation Class. Name variable. Name(arguments); q string flower(“tulip”);
Assigning value later n Long version string flower; string name; flower = string(“Rose”); name = string(“Pete”); n Shorter version flower = “Rose”; name = “Pete”; Special assignment for strings
Creating examples n n n n Assume: char buffer[] = “hi”; string s 0(“string”); string s 1; string s 2(s 0); string s 3(buffer); string s 4(buffer, 1); string s 5(5, ‘f’);
String Concatenation n Use the plus operator to join Strings together ‘+’ is the concatenation operator q Example: string full. Name = name + “ “ + flower; q full. Name holds the value “Pete Rose”
String Methods n n 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. sub. String(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 n n 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(); n What is the result? q saying. at(0); n What is the result? q saying. at(saying. length() – 1); n What is the result? q
String Methods Examples saying = “C++ is fun!” saying. substr(5, saying. length()); n What is the result? q saying. substring(0, 3); n What is the result? q saying. find(“C++”); n What is the result? q saying. find(“c++”); n What is the result? q
Displaying and Storing Method Results n Use assignment statements to store the result of a method call q int pos. Blank = saying. find(“ “); n pos. Blank stores the value 3 String first. Word = saying. substr(0, pos. Blank); q n n first. Word store the value “C++” Including the method call in the output statement cout << “The first blank is a position “ << saying. find(“ “)); q
Object-Oriented Design n Program divided into 2 parts q q Application n File that contains main n Create and manipulate one or more worker objects Worker classes n n Contain methods that perform different kinds of operations Example: string
6. 1 Introduction n Object-oriented programming (OOP) q n Information hiding q q n Encapsulates data (attributes) and functions (behavior) into packages called classes Class objects communicate across well-defined interfaces Implementation details hidden within classes themselves User-defined (programmer-defined) types: classes q q Data (data members) Functions (member functions or methods) Similar to blueprints – reusable Class instance: object
Developing a Worker Class The class definition q q q Data field declarations Constructor definitions Method definitions
Library Book Example n Data Fields q q title author date due who checked the book out n Methods q q q q q get title get author get due date get lendee calculate overdue fine calculate days until due check out renew check in
Data Fields n n n 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 q type. Name data. Field. Name; q Examples n n int pennies; string month;
Library Book Declarationtitle class Library. Book { private: public: }; author date due who checked the book out
Constructor Definitions n n n 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 constructor class Library. Book { private: string title; string author; string borrower; My. Date due. Date; public: // Construtor };
Method Declarations n Method prototype q q species the name of the method data type of the value returned parameters in parentheses Form n n result. Type method. Name([parameter list]) Example: q q double get. Price(); void set. Price(double);
Library Book – Adding the Methods class Library. Book { private: string title; string author; string borrower; My. Date due. Date; public: // Construtor Library. Book(string t, String a); // Return title // Returns due. Date // Checks out book // Checks book in }; Found in the file: Library. Book. h get title get due date check out check in
Calling Methods n A call to a method is considered a statement q For methods return void n q Example: book 1. checkin(); For methods returning a value (non-void), you should store the value in a variable or use the value Example: string out = “Title – “ + book 1. get. Title(); n
Postconditions n Comments that precede a method q n n Tell user of the class what will be true after the method is called Part of the documentation Examples q Method returns the title of the book n q // postcondition: returns the title of this book Method checks in a book n // postcondition: sets borrower to empty string and due. Date to default value
6. 6 Class Scope and Accessing Class Members n Class scope q q Data members, member functions Within class scope n Class members q q q Outside class scope n Referenced through handles q n Immediately accessible by all member functions Referenced by name Object name, reference to object, pointer to object File scope q Nonmember functions
6. 6 Class Scope and Accessing Class Members n Function scope q q q Variables declared in member function Only known to function Variables with same name as class-scope variables n Class-scope variable “hidden” q q q Access with scope resolution operator (: : ) Class. Name: : class. Variable. Name Variables only known to function they are defined in Variables are destroyed after function completion
Library Book Method definitions Constructor n Form: class. Name: : method. Name([parameters]) Purpose is to initialize the data fields n Library. Book: : Library. Book(string t, string a) { }
Writing code for Library Book Methods string Library. Book: : get. Title() { return title; } Date Library. Book: : get. Due. Date() { return due. Date; } void Library. Book: : checkout(string name, My. Date due) { borrower = name; due. Date = due; } void Library. Book: : checkin() { borrower = “”; due. Date = My. Date(); } Found in the file: Library. Book. cpp
Ways to Create Strings string s; Default constructor. Creates an empty string s (str); Copy constructor. Creates a new string s as a copy of another string, string s(str, indx); Creates a new string s from characters starting at index indx of string s(str, indx, count); Creates a new string s initialized by at most count characters from str, starting at index indx in string s(cstr); Creates a new string s initialized with characters from the cstring cstr string s(char. Array, count); Creates a new string s initialized with at most count characters from char array char. Array 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(new. Size, Changes the size of s to new. Size, pad. Char) filling with repetitions of the character pad. Char 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 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
string Comparisons s 1 == s 2 Returns true if all characters of s 1 and s 2 are pairwise equal, else turns false s 1 != s 2 Returns true if not all characters of s 1 and s 2 are pairwise equal, else returns false s 1 < s 2 Returns true if s 1 comes before s 2 lexicographically, else returns false s 1 > s 2 Returns true if s 1 comes after s 2 lexicographically, else returns false s 1 <= s 2 Same as !(s 1 > s 2) S 1 >= s 2 Same as !(s 1 < s 2) Lexicographic ordering compares characters at corresponding positions sequentially until a position i is found where s 1[i] ≠ s 2[i]. Then the expression s 1 < s 2 has the same Boolean value as s 1[i] < s 2[i].
string I/O Operations os << 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, Reads characters from stream is into string str, delimiter) 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // Fig. 8. 13: fig 08_13. cpp // Standard library string class test program. #include <iostream> using std: : cout; using std: : endl; #include <string> using std: : string; int main() { string s 1( "happy" ); string s 2( " birthday" ); string s 3; // test overloaded equality and relational operators cout << "s 1 is "" << s 1 << ""; s 2 is "" << s 2 << ""; s 3 is "" << s 3 << '"' << "nn. The results of comparing s 2 and s 1: " << "ns 2 == s 1 yields " << ( s 2 == s 1 ? "true" : "false" ) << "ns 2 != s 1 yields " << ( s 2 != s 1 ? "true" : "false" ) fig 08_13. cpp (1 of 4)
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 << "ns 2 > s 1 yields " << ( s 2 > s 1 ? "true" : "false" ) << "ns 2 < s 1 yields " << ( s 2 < s 1 ? "true" : "false" ) << "ns 2 >= s 1 yields " << ( s 2 >= s 1 ? "true" : "false" ) << "ns 2 <= s 1 yields " << ( s 2 <= s 1 ? "true" : "false" ); // test string member function empty cout << "nn. Testing s 3. empty(): n"; if ( s 3. empty() ) { cout << "s 3 is empty; assigning s 1 to s 3; n"; s 3 = s 1; // assign s 1 to s 3 cout << "s 3 is "" << s 3 << """; } // test overloaded string concatenation operator cout << "nns 1 += s 2 yields s 1 = "; s 1 += s 2; // test overloaded concatenation cout << s 1; fig 08_13. cp p (2 of 4)
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 // test overloaded string concatenation operator // with C-style string cout << "nns 1 += " to you" yieldsn"; s 1 += " to you"; cout << "s 1 = " << s 1 << "nn"; // test string member function substr cout << "The substring of s 1 starting at location 0 forn" << "14 characters, s 1. substr(0, 14), is: n" << s 1. substr( 0, 14 ) << "nn"; // test substr "to-end-of-string" option cout << "The substring of s 1 starting atn" << "location 15, s 1. substr(15), is: n" << s 1. substr( 15 ) << 'n'; fig 08_13. cpp (3 of 4)
58 59 60 61 62 63 64 65 66 67 68 69 70 // test using subscript operator to create lvalue s 1[ 0 ] = 'H'; s 1[ 6 ] = 'B'; cout << "ns 1 after s 1[0] = 'H' and s 1[6] = 'B' is: " << s 1 << "nn"; // test subscript out of range with string member function "at" cout << "Attempt to assign 'd' to s 1. at( 30 ) yields: " << endl; s 1. at( 30 ) = 'd'; // ERROR: subscript out of range return 0; } // end main fig 08_13. cp p (4 of 4)
s 1 is "happy"; s 2 is " birthday"; s 3 is "" The results of comparing s 2 and s 1: s 2 == s 1 yields false s 2 != s 1 yields true s 2 > s 1 yields false s 2 < s 1 yields true s 2 >= s 1 yields false s 2 <= s 1 yields true Testing s 3. empty(): s 3 is empty; assigning s 1 to s 3; s 3 is "happy" s 1 += s 2 yields s 1 = happy birthday fig 08_13. cpp output (1 of 2)
s 1 += " to you" yields s 1 = happy birthday to you The substring of s 1 starting at location 0 for 14 characters, s 1. substr(0, 14), is: happy birthday fig 08_13. cpp output (2 of 2) The substring of s 1 starting at location 15, s 1. substr(15), is: to you s 1 after s 1[0] = 'H' and s 1[6] = 'B' is: Happy Birthday to you Attempt to assign 'd' to s 1. at( 30 ) yields: abnormal program termination
- Slides: 42