1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.

Slides:



Advertisements
Similar presentations
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
MSc IT Programming Methodology (2). number name number.
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.
What have we learned so far… Preprocessor directives Introduction to C++ Variable Declaration Display Messages on Screen Get Information from User Performed.
1 Classes Object-oriented programming: Model the problem as a collection of objects that have certain attributes and interact with one another and/or the.
1 Using Classes and Working With Class Interfaces November 20, 2002 CSE103 - Penn State University Prepared by Doug Hogan.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
ACM/JETT Workshop - August 4-5, Object-Oriented Basics & Design.
C++ fundamentals.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
Introduction to Classes and Objects (Through Ch 5) Dr. John P. Abraham Professor UTPA.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Writing Classes (Chapter 4)
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
Working with Strings Lecture 2 Hartmut Kaiser
Basic Object- Oriented Concepts Presented By: George Pefanis 21-Sep-15.
1.  A method describes the internal mechanisms that actually perform its tasks  A class is used to house (among other things) a method ◦ A class that.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Object-Oriented Programming in C++
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
CSCI-383 Object-Oriented Programming & Design Lecture 5.
DATA STRUCTURES LAB 1 TA: Nouf Al-harbi
CSCI 383 Object-Oriented Programming & Design Lecture 6 Martin van Bommel.
ECE 264 Object-Oriented Software Development Instructor: Dr. Honggang Fall 2012 Lecture 8: File I/O; Introduction to classes.
1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
1 Warm-Up Problem Just like with primitive data types (int, double, etc.), we can create arrays of objects. ex: bankAccount employees[100]; Problem: It’s.
Classes: Member Functions and Implementation November 22, 2002 CSE103 - Penn State University Prepared by Doug Hogan.
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
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.
C++ Lecture 1 Friday, 4 July History of C++ l Built on top of C l C was developed in early 70s from B and BCPL l Object oriented programming paradigm.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C++ Classes and Data Structures Jeffrey S. Childs
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Chapter 1: Object Oriented Paradigm. 1.1 Data Abstraction and Encapsulation OOP allows programmer to – separate the details that are important to the.
ACM/JETT Workshop - August 4-5, : Defining Classes in Java.
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.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Intro to Classes via the C++ String Class November 18, 2002 CSE103 - Penn State University Online at
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
Unit 3 Lesson 5 Strings and the String Class Mr. Dave Clausen (modifications from the textbook)
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Classes and.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Library Functions. CSCE 1062 Outline  cmath class library functions {section 3.2}  iomanip class library functions {section 8.5}  string class library.
Chapter 4 Strings and Screen I/O. Objectives Define strings and literals. Explain classes and objects. Use the string class to store strings. Perform.
1 C++ Classes and Data Structures Course link…..
Lecture Overview Linked List quiz Finish last class' topic:
Classes C++ representation of an object
Working with Strings Lecture 2 Hartmut Kaiser
Classes Object-oriented programming: Example: Bank transactions
Classes: Implementation and Testing
Working with Strings Lecture 2 Hartmut Kaiser
Sending Messages Chapter 5 Computing Fundamentals with C++ 3rd Edition
Chapter 6 Class Definitions and Member Functions
Wednesday 09/23/13.
From C to C++: Summary of weeks 1 - 4
By Rajanikanth B OOP Concepts By Rajanikanth B
Classes C++ representation of an object
Chapter 9 Introduction To Classes
Programming Strings.
Presentation transcript:

1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan

2 Overview  String class  Headers  Creating strings  Manipulating and comparing strings  Motivation for Object Oriented Programming  Strings as objects  Terminology and theory  Another custom class  Objects vs. classes  Access rights  Using a class interface

3 The string type  Alternative to character arrays  Hides many details  Easier to manipulate  Required headers  #include  using namespace std;  string is part of the C++ standard library

4 Declaring strings  Uninitialized:  Like primitive data types  e.g. string myString;  Can then use assignment operator  e.g. myString = “this is a string”;  Initialized:  Use string keyword, name, and initial value in parentheses  e.g. string myString(“a string”);

5 Input/Output  cin and cout  cin stops at whitespace  getline can be used for reading in strings with spaces included:  getline(stream, receivingString);  example:  cout << “Enter a string”; getline(cin, str1);

6 Manipulating Characters  Exactly the same as with arrays of characters!  Use an index in brackets to get or manipulate that character.  string myString(“a string”);  cout << myString[0];  prints “a”  myString[0] = “A”;  changes myString to “A string”

7 Exercises (you do on paper)  Create a string called testString that is initially “Welcome to CMPSC 122”  string testString("Welcome to CMPSC 122");  Change the course number to 121 instead  testString[19] = '1';  Output the string  cout << testString;

8 Operators and strings  The string class lets you use the following operators:  Assignment: =  Comparison: >=, >, <, <=  Equality: ==, !=  Concatenation: +  Example:  if(string1 < string2) { cout << string1 << " is before " << string2 << endl; }

9 Problem  Suppose you have these declarations:  string str1 = "I love ";  string str2 = "computer programming!";  Create a string called str3 from these two strings that reads "I love computer programming!"  string str3 = str1 + str2;

10 A bit of terminology before the fun part…  We’ll call string variables objects.  We can operate on strings with functions  use dot notation  e.g. objectName.operation();  said to be sending a message to the string object

11 length() message  length( ) returns the length of the string it’s called on  ex:  string hello("Hello");  cout << hello.length() << endl;  prints 5  Don’t forget the parentheses!!  Must give the string object, then the dot operator!!

12 Practice  Given  string noun;  cin >> noun;  Output the length of noun.  cout << noun.length();

13 find() message  find( ) takes a string as an argument  returns the index where the argument is found in the object it’s called on  ex:  string hello("Hello");  cout << hello.find("ll") << endl;  prints 2  if the string isn’t found, find( ) returns -1

14 Substrings: substr() message  Takes two integer arguments:  first is starting character  second is length  returns a substring of the given length  string hello("Hello World");  cout << hello.substr(6, 5); << endl;  prints “World”  goes up to string’s length if 2 nd argument is too short

15 Problems  Given string s1("abcdefghi");  string s2(s1.substr(4, 3)); What is stored in s2 ?  Answer: efg  Write a line of code to store the location of the letter “d” from s1 in the following integer:  int d;  Answer: d = s1.find("d");

16 Given string s("Any string"); Give the result of each message or what is wrong with it.  length(s)  s.length  s(length)  s.length()  Find("Any")  s.find(” ")  s.substr(2)  s.substr(2, 5)  s.substr("tri")  s.find("tri") Modified Self-Check 4-8 from: Mercer, Rick. Computing Fundamentals with C++. Wilsonville, OR: Franklin, 1999.

17 Given string s("Any string"); Give the result of each message or what is wrong with it.  length(s)  no dot notation  length takes no argument  s.length  no parentheses  s(length)  parentheses misplaced  s.length()  10  Find("Any")  no object  s.find(" ") 33  s.substr(2)  not enough arguments  s.substr(2, 5)  y str  s.substr("tri")  wrong arguments  s.find("tri") 55 Modified Self-Check 4-8 from: Mercer, Rick. Computing Fundamentals with C++. Wilsonville, OR: Franklin, 1999.

18 Motivation for classes  Object-Oriented Programming (OOP)  Package together a set of related data and operations (encapsulation)  Define a class (abstract data type), or a new data type with its operations  One instance of a class is called an object  The data and operations of a class are called its members.  string is an example of a class

19 Access rights in OOP  Classes are similar to struct s  Add the notion of access rights  class member data and operations can be  public – accessible to anyone  private – accessible only to the object  usually  data are private  operations are public

20 An example of a class: bankAccount  Data:  name  balance  Operations:  create an account  withdraw  deposit  check balance

21 Problem  Write down an example of a bankAccount object.

22 Bank Account Objects  Objects are instances of the class  One class, many objects name balance acct1 $ Marge name balance acct2 $ Bart name balance acct3 $20.00 Homer

23 Class Interface  Starting point for working with classes  Defines the class  Defines the WHAT, not the HOW

24 So what does a class interface look like? #include // string class definition using namespace std;// so std:: isn’t needed class bankAccount { public: bankAccount(); // POST: default bankAccount object constructed with name == “?” and balance == 0 void withdraw(int amount); // PRE: amount in dollars and amount > $0 // POST: amount has been subtracted from balance void deposit(int amount); // PRE: amount in dollars and amount > $0 // POST: amount had been added on to balance double getBalance(); // POST: FCTVAL == balance private: string name; // full name of account holder double balance; // how much in the acct, in dollars }; necessary headers ‘class’ keyword to signal a class definition name of the class declarations of the member functions of the class (public section) declarations of the member data of the class (private section) note the semicolon!!!

25 What do public and private mean?  Public  can be accessed by any function in any class  Private  can only be accessed by functions who are members of the same class  Observations  public member functions  private data  why?  abstraction and information hiding  protect the data from accidental changes

26 Some more observations  Data are declared, but not initialized  Functions are declared, but not implemented  PRE- and POST- conditions are essential

27 So how do we use it?  For now, we will be the client or user.  Create a bankAccount using a special function called a constructor.  The constructor we have: bankAccount();  Called in odd way…  in the declaration: bankAccount myAcct;

28 So how do we use it?  To “do stuff” to or with our object, we need to send it messages.  Use the dot notation we learned for strings.  objectName. operation(parameters?)  Why?  need to say WHICH object to send the message to  Example  Given: bankAccount myAcct;  To deposit $50, myAcct.deposit(50);

29 Time for you to think…  Create two accounts.  Deposit $100 in the first and $75 in the second.  Then withdraw $50 from both.

30 Time for you to think…  Create two accounts.  bankAccount acct1;  bankAccount acct2;  Deposit $100 in the first and $75 in the second.  acct1.deposit(100);  acct2.deposit(75);  Then withdraw $50 from both.  acct1.withdraw(50);  acct2.withdraw(50); name balance acct1 $0.00 ? name balance acct2 $0.00 ? name balance acct1 $ ? name balance acct2 $75.00 ? name balance acct1 $50.00 ? name balance acct2 $25.00 ?

31 More thinking…  How can we print out how much money we have in each account?  balance is private  must send a message!  cout << acct1.getBalance(); // displays 50  cout << acct2.getBalance(); // displays 25  Our bankAccount interface isn’t perfect…  How could it be improved? name balance acct1 $50.00 ? name balance acct2 $25.00 ?