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.

Slides:



Advertisements
Similar presentations
Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
Advertisements

LECTURE 17 C++ Strings 18. 2Strings Creating String Objects 18 C-string C++ - string \0 Array of chars that is null terminated (‘\0’). Object.
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 21: Strings (cont.)
Strings.
C++ Data Type String A string is a sequence of characters enclosed in double quotes. Examples of strings: “Hello” “CIS 260” “Students” The empty string.
1 Lecture 19:String Data Type Introduction to Computer Science Spring 2006.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
Lecture 18:Topic: I/O Formatting and Files Dale/Weems/Headington
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
1 Lecture 5: Input/Output (I) Introduction to Computer Science Spring 2006.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 3: Input/Output.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
1 Lecture 7 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 3: Input/Output
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
In Addition... To the string class from the standard library accessed by #include C++ also has another library of string functions for C strings that can.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Working with Strings Lecture 2 Hartmut Kaiser
1 Chapter 4 Program Input and the Software Design Process.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 3: Input/Output.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 3: Input/Output.
Lecture 6: Expressions and Interactivity (Part II) Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 3 Formatting Output.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output.
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:
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Spring 2013 Lecture 5: Continuing with C++ I/O Basics.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.
Chapter 3: Input/Output
1 Character Strings (Cstrings) Reference: CS215 textbook pages
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
Homework #4: Operator Overloading and Strings By J. H. Wang Apr. 17, 2009.
Chapter 9 Strings. Learning Objectives An Array Type for Strings – C-Strings Character Manipulation Tools – Character I/O – get, put member functions.
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
An Introduction to Programming with C++ Sixth Edition Chapter 13 Strings.
Intro to Classes via the C++ String Class November 18, 2002 CSE103 - Penn State University Online at
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
Program Input and the Software Design Process ROBERT REAVES.
Input/Output. Objectives In this chapter you will: Learn what a stream is and examine input and output streams Explore how to use the input stream functions.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 15, 2004 Lecture Number: 11.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Lecture Overview Linked List quiz Finish last class' topic:
Topic 2 Input/Output.
Working with Strings Lecture 2 Hartmut Kaiser
Chapter 3: Expressions and Interactivity.
SAS in Data Cleaning.
C++ STRINGS string is part of the Standard C++ Library
Working with Strings Lecture 2 Hartmut Kaiser
Operator Overloading; String and Array Objects
10.1 Character Testing.
Wednesday 09/23/13.
Chapter 3 Input output.
Programs written in C and C++ can run on many different computers
Instructor: Dr. Michael Geiger Spring 2019 Lecture 13: Exam 1 Preview
COMS 261 Computer Science I
Today’s Objectives 28-Jun-2006 Announcements
Programming Strings.
Instructor: Dr. Michael Geiger Spring 2019 Lecture 6: Strings
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

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 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 instantiation ClassName variableName(arguments);  string flower(“tulip”);

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

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 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?  saying.at(0); What is the result?  saying.at(saying.length() – 1); What is the result? 

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

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: public: }; title author date due who 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 constructor class LibraryBook { private: string title; string author; string borrower; MyDate dueDate; public: // Construtor };

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

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 definitions Constructor Form: className::methodName([parameters]) Purpose is to initialize the data fields LibraryBook::LibraryBook(string t, string a) { }

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

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

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 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 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].

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:

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" )

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;

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

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

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)

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)