Presentation is loading. Please wait.

Presentation is loading. Please wait.

Classes and Data Abstraction Lecture 9. Objects Models of things in the real world Defined in classes  Class name is the object name Example: Library.

Similar presentations


Presentation on theme: "Classes and Data Abstraction Lecture 9. Objects Models of things in the real world Defined in classes  Class name is the object name Example: Library."— Presentation transcript:

1 Classes and Data Abstraction Lecture 9

2 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

3 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

4 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?

5 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

6 Strings 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”);

7 Assigning value later Long version string flower; string name; flower = string(“Rose”); name = string(“Pete”); Shorter version flower = “Rose”; name = “Pete”; Special assignment for strings

8 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’);

9 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”

10 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

11 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

12 String 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? 

13 String Methods Examples 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?  saying = “C++ is fun!”

14 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(“ “));

15 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

16 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

17 Developing a Worker Class The class definition  Data field declarations  Constructor definitions  Method definitions

18 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

19 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;

20 Library Book Declaration class LibraryBook { private: public: }; title author date due who checked the book out

21 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

22 Library Book – adding the constructor class LibraryBook { private: string title; string author; string borrower; MyDate dueDate; public: // Construtor };

23 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);

24 Library 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 // Checks book in }; get title get due date check out check in Found in the file: LibraryBook.h

25 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();

26 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

27 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

28 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

29 Library Book Method definitions Constructor Form: className::methodName([parameters]) Purpose is to initialize the data fields LibraryBook::LibraryBook(string t, string a) { }

30 Writing code for Library Book Methods string 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

31 Ways 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

32 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()

33 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

34 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

35 string 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 < 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 sequentially until 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].

36 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, 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:

37 fig08_13.cpp (1 of 4) 1 // Fig. 8.13: fig08_13.cpp 2 // Standard library string class test program. 3 #include 4 using std::cout; 5 using std::endl; 6 #include 7 using std::string; 8 9 int main() { 10 string s1( "happy" ); 11 string s2( " birthday" ); 12 string s3; // 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" )

38 fig08_13.cpp (2 of 4) 21 s1 yields " 22 s1 ? "true" : "false" ) 23 << "\ns2 < s1 yields " 24 << ( s2 < s1 ? "true" : "false" ) 25 = s1 yields " 26 = s1 ? "true" : "false" ) 27 << "\ns2 <= s1 yields " 28 << ( s2 <= s1 ? "true" : "false" ); // 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 } // test overloaded string concatenation operator 39 cout << "\n\ns1 += s2 yields s1 = "; 40 s1 += s2; // test overloaded concatenation 41 cout << s1;

39 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"; // 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"; // 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

40 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"; // 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 return 0; } // end main

41 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.cpp output (1 of 2)

42 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.cpp output (2 of 2)


Download ppt "Classes and Data Abstraction Lecture 9. Objects Models of things in the real world Defined in classes  Class name is the object name Example: Library."

Similar presentations


Ads by Google