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:

Slides:



Advertisements
Similar presentations
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.
Advertisements

Chapter 10 Introduction to Arrays
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
Today’s Class Class string –The basics –Assignment –Concatenation –Compare & swap –Find –Conversion to C-style char * strings –Iterators.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Introduction to Classes and Data Abstraction
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Review of C++ Programming Part II Sheng-Fang Huang.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Chapter 8 Strings and Vectors (8.1 and 8.2). An Array of characters Defined as: char firstName[20]; char firstName[] = {‘T’, ‘i’, ‘m’}; // an array of.
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.
Working with Strings Lecture 2 Hartmut Kaiser
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
C++ Lecture 4 Tuesday, 15 July Struct & Classes l Structure in C++ l Classes and data abstraction l Class scope l Constructors and destructors l.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Fall 2012 Lecture 8: File I/O; Introduction to classes.
1 Classes and Data Abstraction Part II Initializing Class Objects: Constructors Constructors  Initialize data members  Same name as class 
Chapter 10 Introduction to Classes
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
String Class. C-style and C++ string Classes C-style strings, called C-strings, consist of characters stored in an array ( we’ll look at them later) C++
1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
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.
String Class Mohamed Shehata 1020: Introduction to Programming.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
1 CSC 222: Computer Programming II Spring 2004  classes and objects  abstract data types, classes and objects  using existing classes, #include, member.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
C++ STRINGS ● string is part of the Standard C++ Library ● new stuff: ● cin : standard input stream (normally the keyboard) of type istream. ● >> operator.
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Wang Fall 2012 Lecture 20: Container classes; strings.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Lecture Overview Linked List quiz Finish last class' topic:
Introduction to C++ Systems Programming.
Working with Strings Lecture 2 Hartmut Kaiser
Announcements 2nd homework is due this week Wednesday (October 18)
Introduction to Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
C++ STRINGS string is part of the Standard C++ Library
Operator Overloading; String and Array Objects
Working with Strings Lecture 2 Hartmut Kaiser
Operator Overloading; String and Array Objects
Learning Objectives Classes Constructors Principles of OOP
Announcements 3rd homework is due this week Wednesday (March 15)
Introduction to Classes and Objects
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Object Oriented Programming in java
Today’s Objectives 28-Jun-2006 Announcements
Instructor: Dr. Michael Geiger Spring 2019 Lecture 6: Strings
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Classes and Objects Systems Programming.
Presentation 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 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 Ø 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 0 saying.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: }; 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 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 Methods class 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 title set 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) { title = t; author = a; borrower = “"; // book is not currently // checked out dueDate = MyDate(); }

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)

Example Original Array Array After 2 nd Pass Array After 1 st Pass Array After 3 rd Pass Table [0][1][2][3]…[n-1] [0] [1] [2] [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 1 st Pass

Example Original Array Array After 2 nd Pass Array After 1 st Pass Array After 3 rd Pass Table [0][1][2][3]…[n-1] [0] [1] [2] 124 [3] 432 [4] [5] [6] [7] 976 [8] [9] 999 Doing the same process for the tens place

Example Original Array Array After 2 nd Pass Array After 1 st Pass Array After 3 rd Pass Table [0][1][2][3]…[n-1] [0] 001 [1] [2] [3] [4] [5] [6] [7] [8] 800 [9] Doing the same process for the hundreds place