1 Today’s Objectives Announcements Turn in Homework #1 Homework #2 is posted and it is due on...

38
1 Today’s Objectives Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun Review Quiz #1 Pointers and C-style strings (Ch. 5) Pointer variables – declaration and initialization Operators * and & Pass-by-reference using pointers Using const with pointers Arrays, pointers, and dynamic allocation of arrays with new C-style strings C++ string class (Ch. 18) Using a vector as a data member of a class Bonus Lab 12-Jun-2006

Transcript of 1 Today’s Objectives Announcements Turn in Homework #1 Homework #2 is posted and it is due on...

Page 1: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

1

Today’s ObjectivesToday’s Objectives

Announcements• Turn in Homework #1• Homework #2 is posted and it is due on 21-Jun

Review Quiz #1

Pointers and C-style strings (Ch. 5)• Pointer variables – declaration and initialization• Operators * and &• Pass-by-reference using pointers• Using const with pointers• Arrays, pointers, and dynamic allocation of arrays with new• C-style strings• C++ string class (Ch. 18)

Using a vector as a data member of a class

Bonus Lab

12-Jun-200612-Jun-2006

Page 2: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

2

Review Quiz #1Review Quiz #1

Answers are posted in the “Files” area on the class discussion group site

Page 3: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

3

PointersPointers

Chapter 8

Page 4: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

4

Regular VariablesRegular Variables

Variables are used to keep track of data in the computer’s memory.

Declaring a regular variable = Allocating a location inmemory to store a value

• Example:int myInt = 0; //Allocates enough space in memory //to store an int and puts 0 there

The location in memory has an address

Use operator & to get the address• Example:cout << "Address of myInt = " << &myInt << endl;

Pointers and C-Style Strings (Deitel, 402)Pointers and C-Style Strings (Deitel, 402)

Page 5: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

5

Pointer VariablesPointer Variables

A pointer variable is used to hold an address

Use operator * to declare a pointer variable• Example:int *pMyInt; //Declares an empty pointer

An address must be assigned to the pointer variablebefore it can be used

int myInt = 0; //Allocates memory, stores 0int *pMyInt; //Declares an empty pointerpMyInt = &myInt; //Puts an address in the pointer

Pointers and C-Style Strings (Deitel, 402)Pointers and C-Style Strings (Deitel, 402)

Page 6: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

6

Dereferencing a PointerDereferencing a Pointer

Accessing the object addressed by the pointer Operator * used with the name of the pointer, after it is

declared and initialized Examples

int myInt = 0; //Allocates memory, stores 0int *pMyInt; //Declares an empty pointerpMyInt = &myInt; //Puts address in the pointer

cout << *pMyInt << endl; //Prints 0

*pMyInt = 5; //puts 5 into myInt

cout << myInt << endl;//Prints 5

cout << *pMyInt << endl; //Also prints 5

cout << pMyInt << endl; //What prints?

Pointers and C-Style Strings (Deitel, 405)Pointers and C-Style Strings (Deitel, 405)

Page 7: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

7

Where are the errors?Where are the errors?

int main(){

int m; int *pm; *pm = 5;

int n; int *pn = &n; pn = 5;

}

Pointers and C-Style StringsPointers and C-Style Strings

Page 8: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

8

Where are the errors?Where are the errors?

int main(){

int m; int *pm; *pm = 5;

int n; int *pn = &n; pn = 5;

}

Pointers and C-Style StringsPointers and C-Style Strings

ERROR! No address in pm//Correctionpm = &m;*pm = 5;

Page 9: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

9

Where are the errors?Where are the errors?

int main(){

int m; int *pm; *pm = 5;

int n; int *pn = &n; pn = 5;

}

Pointers and C-Style StringsPointers and C-Style Strings

ERROR! No address in pm//Correctionpm = &m;*pm = 5;

ERROR! Missing operator*//Correction*pn = 5;

Page 10: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

10

Pointer ExercisesPointer Exercises

Handout

Pointers and C-Style StringsPointers and C-Style Strings

Page 11: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

11

Pass-by-Reference Using PointersPass-by-Reference Using Pointers

Pass-by-reference• Means that the function arguments are used to pass data both

into and out of a function• Changes to the variable in the function are passed to the

calling variable.• One way to do it is by using a reference parameter or “alias”

void change( int &rn ){ //rn is a referencern = rn + rn;

}

Pointers can also be used for pass-by-referencevoid change( int *pn ){ //pn is a pointer*pn = *pn + 1;

}

Pointers and C-Style Strings (Deitel, 407)Pointers and C-Style Strings (Deitel, 407)

Page 12: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

12

Pass-by-Reference Using PointersPass-by-Reference Using Pointers

void change( int *pn ){ //pn is a pointer*pn += *pn; //Dereferencing with operator *

}

int main(){ int num = 5; change( &num ); //Using operator & cout << num << endl; //What prints?

int *pNum; pNum = &num; change( pNum ); //Using a pointer argument cout << num << endl; //What prints?}

Pointers and C-Style Strings (Deitel, 407)Pointers and C-Style Strings (Deitel, 407)

Page 13: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

13

Using const with PointersUsing const with Pointers

We use pass-by-reference to make our programs more efficient. In this approach, no copies of the arguments are made inside the function.

Sometimes we want the efficiency of using pass-by-reference, but we don’t want to change the argument that is passed, so we use “const” to make the argument unchangeable

void noChange( const int *pn ){ //Now *pn cannot be changedcout << "Inside the function *pn = " << *pn << endl;

}int main(){ int num = 5; noChange( &num ); cout << num << endl;}

Pointers and C-Style Strings (Deitel, 411)Pointers and C-Style Strings (Deitel, 411)

Page 14: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

14

Pointers & ArraysPointers & Arrays

The array name is a pointer to the first elementconst int CAPACITY = 5;int myArray[CAPACITY] = {0};cout << myArray; //Prints address of myArray[0]cout << &myArray[0]; //Prints the same address

int *pMyArray = myArray; //Initialize a pointer

myArray[0] = 8;cout << myArray[0] << endl; //Prints 8cout << *pMyArray << endl; //Prints 8

Pointers and C-Style Strings (Deitel, 427)Pointers and C-Style Strings (Deitel, 427)

Page 15: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

15

Pointer ArithmeticPointer Arithmetic

When a pointer points to an array, we can use ++, --, +=, and -= to move through the array.int myArray[] = {1,2,3,4,5};int *pMyArray = myArray;

cout << *pMyArray << endl; //Prints 1pMyArray++;cout << *pMyArray << endl; //Prints 2pMyArray += 2;cout << *pMyArray << endl; //Prints 4

Pointers and C-Style Strings (Deitel, 424)Pointers and C-Style Strings (Deitel, 424)

Page 16: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

16

Dynamically Allocating ArraysDynamically Allocating Arrays

Arrays can be allocated with “new” “new” allocates a section of memory for the array, and

then returns a pointer to it. Useful when you don’t know how large the array will be

until the program is runningint capacity, *myArray;cin >> capacity;myArray = new int[capacity];//Creates the array

for( int i=0; i<capacity; ++i ) //Initialize it myArray[i] = i;cout << myArray[0] << endl; //Prints 0delete [] myArray;

Pointers and C-Style StringsPointers and C-Style Strings

Page 17: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

17

Using deleteUsing delete

Memory allocated with “new” must always be recovered by “delete”

Always “delete” an array when you don’t need it anymore if you created it with “new”

delete [] myArray;

Pointers and C-Style StringsPointers and C-Style Strings

Page 18: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

18

C-Style StringsC-Style Strings

Chapter 8

Page 19: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

19

C-style StringsC-style Strings

In C, strings are treated as arrays of type char that end with the null character, ‘\0’. This also works in C++

There are several ways to initialize themchar *beatle1 = "John";char beatle2[5] = "Paul";char beatle3[] = {'G','e','o','r','g','e','\0'};cout << "The first three Beatles were " << beatle1 << " " << beatle2 << " " << beatle3 << endl;

If you use the char* syntax, you can change the string beatle1 = "Ringo";

Pointers and C-Style Strings (Deitel, 443)Pointers and C-Style Strings (Deitel, 443)

J o h n \00 1 2 3 4

Page 20: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

20

Input of C-style StringsInput of C-style Strings

Strings can be input using cinchar beatle[50];cout << "Enter a Beatle: ";cin >> beatle;cout << "One of the Beatles was " << beatle;

Better method is to limit the size of the inputconst char CAPACITY = 50;char buffer[CAPACITY];cout << "Enter all four Beatles ";cin.getline( buffer, CAPACITY );cout << buffer << endl;

Pointers and C-Style Strings (Deitel, 443)Pointers and C-Style Strings (Deitel, 443)

Page 21: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

21

Functions for C-style StringsFunctions for C-style Strings

//Copy one string to anotherchar marx[] = "Groucho";strcpy( marx, "Karl");

//Compare two stringschar marx1[] = "Harpo";char marx2[] = "Chico";int result = strcmp( marx1, marx2 );//0 if equal

//Length of a stringint length = strlen( marx1 );//returns 5

Pointers and C-Style Strings (Deitel, 446)Pointers and C-Style Strings (Deitel, 446)

Page 22: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

22

C++ string ClassC++ string Class

A better, object-oriented approach#include <string>using namespace std;

int main(){ string input, secret="UHCL", welcome="Welcome!"; string greeting = "Enter the password"; cout << greeting << endl; cout << "It has " << secret.size() << " letters."; cin >> input; if( input == secret ){ greeting = welcome; cout << greeting; }}

Pointers and C-Style Strings (Deitel, 884)Pointers and C-Style Strings (Deitel, 884)

Page 23: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

23

Using a vector as a data member of a class

Using a vector as a data member of a class

Homework 2, Problem #3

Page 24: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

24

Homework 2, Problem #3Homework 2, Problem #3

Implement the classes for Customer and Store as shown in the class diagram

• Each class shall be in its own header file• Customer.h and Store.h

Create an object-oriented C++ program that implements the actions of the following menu items

1 View customer list2 Search for a customer3 Add a customer

• Use the Gigaplex Menu program as the driver program• Add a new menu item called “Add a customer”• Instantiate a Store object in main. When the user selects “View

customer list,” “Search for a customer,” or “Add a customer,” the program shall get any input from the user that might be required, and then call the appropriate operation of the Store object.

Using a vector as a data memberUsing a vector as a data member

Page 25: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

25

UML Class DiagramUML Class Diagram

Customer

– ID : string– firstName : string– lastName : string

+ Customer()+ getID() : string+ setID( in id : string )

class Customer {private: string ID; string firstName; string lastName;public: Customer(); string getID() const { return ID; } void setID( string id ) { ID = id; }};

Class name(The top section)

Scopeprivatepublic

Data members are in the middle section.Member functions are in the bottom section.

Datatype

ParameterReturn datatype

Using a vector as a data memberUsing a vector as a data member

Page 26: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

26

UML Class DiagramUML Class Diagram

class Store{private: //The Store has-a Customer vector<Customer> customers;public: void viewCustomerList(); Customer* searchForCustomer( string id ); void addCustomer( Customer &cust );};

CompositionThe “has-a” relationship

Store

- customers : vector<Customer>

+viewCustomerList()+searchForCustomer(in id: string ) : Customer*+addCustomer(in cust : Customer& )

Customer- ID : string- firstName : string- lastName : string

+ Customer()+ getID() : string+ setID(in id : string )

10..*

Multiplicities1 Store objecthas 0, 1, or manyCustomers

Using a vector as a data memberUsing a vector as a data member

Page 27: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

27

Instantiating a vector ObjectInstantiating a vector Object

#include <vector>using namespace std;int main(){

vector<char> coll;

Instantiate a vector object that will hold char data

Name of the class The object name

Template parameter – type of data the vector will hold

Using a vector as a data memberUsing a vector as a data member

Page 28: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

28

Adding Data to a vector ObjectAdding Data to a vector Object

#include <vector>using namespace std;int main(){

vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');

Add some data

If we need to print the data, we can loop through the data in the vector by using an iterator.

Using a vector as a data memberUsing a vector as a data member

Page 29: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

29

STL IteratorsSTL Iterators

An iterator is a class used to create objects that give us access to the elements inside a container, such as a vector

They are called “iterators” because they are often used to sequentially iterate or “loop” through all the elements in a container

All container classes have their own iterators that are implemented as part of the container class

Using a vector as a data member (Josuttis, 83–86)Using a vector as a data member (Josuttis, 83–86)

Page 30: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

30

Using an STL IteratorUsing an STL Iterator

vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');

Create a vector of chars and put some chars in it

Using a vector as a data member (Josuttis, 83–86)Using a vector as a data member (Josuttis, 83–86)

Page 31: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

31

Using an STL IteratorUsing an STL Iterator

vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');

vector<char>::iterator pos;

Instantiate an iterator that can be used with a vector of chars

Using a vector as a data member (Josuttis, 83–86)Using a vector as a data member (Josuttis, 83–86)

Page 32: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

32

Using an STL IteratorUsing an STL Iterator

vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');

vector<char>::iterator pos;

for( pos = coll.begin(); pos != coll.end(); ++pos)

Create a for loop

Using a vector as a data member (Josuttis, 83–86)Using a vector as a data member (Josuttis, 83–86)

Page 33: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

33

Using an STL IteratorUsing an STL Iterator

vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');

vector<char>::iterator pos;

for( pos = coll.begin(); pos != coll.end(); ++pos)

InitializationAssign a starting value to the iterator

Every collection class has a begin() member function that returns an iterator representing its first element.

Using a vector as a data member (Josuttis, 83–86)Using a vector as a data member (Josuttis, 83–86)

Page 34: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

34

Using an STL IteratorUsing an STL Iterator

vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');

vector<char>::iterator pos;

for( pos = coll.begin(); pos != coll.end(); ++pos)

ConditionLoop is executed only if this is true

Every collection class has a end() member function that returns an iterator representing the position after the last element.

Using a vector as a data member (Josuttis, 83–86)Using a vector as a data member (Josuttis, 83–86)

Page 35: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

35

Using an STL IteratorUsing an STL Iterator

vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');

vector<char>::iterator pos;

for( pos = coll.begin(); pos != coll.end(); ++pos)

In the expression evaluated at the end of each loop, the iterator behaves like a pointer.

Using a vector as a data member (Josuttis, 83–86)Using a vector as a data member (Josuttis, 83–86)

Page 36: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

36

Using an STL IteratorUsing an STL Iterator

vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');

vector<char>::iterator pos;

for( pos = coll.begin(); pos != coll.end(); ++pos){

cout << *pos << " ";}

In the loop, we can use the iterator like a pointer again, so that we can get the value stored at this position.

Using a vector as a data member (Josuttis, 83–86)Using a vector as a data member (Josuttis, 83–86)

Page 37: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

37

Bonus Lab #2Using a vector as a data member in the GradeBook class

Bonus Lab #2Using a vector as a data member in the GradeBook class

Optional Procedure

• First, a demo by the instructor• Then you will complete the assignment on your own• Print it and hand it in before the end of class

Rules• Do your own work, but you may help each other• You may ask the instructor for help• You may leave if you finish early or if you do not wish to do this

assignment

1 bonus point added to a quiz grade for each correctly completed lab handed in before the end of class

Page 38: 1 Today’s Objectives  Announcements Turn in Homework #1 Homework #2 is posted and it is due on 21-Jun  Review Quiz #1  Pointers and C-style strings.

38

ReferencesReferences

Deitel, H. M., and P. J. Deitel, C++ How to Program, Fifth Edition. Upper Saddle River, NJ: Prentice Hall, 2005.

Josuttis, Nicolai M., The C++ Standard Library, A Tutorial and Reference. Boston: Addison-Wesley, 1999.