Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

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

2 2 Review Quiz #1 Answers are posted in the “Files” area on the class discussion group site

3 3 Pointers Chapter 8

4 4 Regular Variables Variables are used to keep track of data in the computer’s memory. Declaring a regular variable =Allocating a location in memory 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)

5 5 Pointer 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 variable before it can be used int myInt = 0;//Allocates memory, stores 0 int *pMyInt;//Declares an empty pointer pMyInt = &myInt;//Puts an address in the pointer Pointers and C-Style Strings (Deitel, 402)

6 6 Dereferencing 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 0 int *pMyInt;//Declares an empty pointer pMyInt = &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)

7 7 Where are the errors? int main(){ int m; int *pm; *pm = 5; int n; int *pn = &n; pn = 5; } Pointers and C-Style Strings

8 8 Where are the errors? int main(){ int m; int *pm; *pm = 5; int n; int *pn = &n; pn = 5; } Pointers and C-Style Strings ERROR! No address in pm //Correction pm = &m; *pm = 5;

9 9 Where are the errors? int main(){ int m; int *pm; *pm = 5; int n; int *pn = &n; pn = 5; } Pointers and C-Style Strings ERROR! No address in pm //Correction pm = &m; *pm = 5; ERROR! Missing operator* //Correction *pn = 5;

10 10 Pointer Exercises Handout Pointers and C-Style Strings

11 11 Pass-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 reference rn = rn + rn; }  Pointers can also be used for pass-by-reference void change( int *pn ){ //pn is a pointer *pn = *pn + 1; } Pointers and C-Style Strings (Deitel, 407)

12 12 Pass-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)

13 13 Using 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 changed cout << "Inside the function *pn = " << *pn << endl; } int main(){ int num = 5; noChange( &num ); cout << num << endl;} Pointers and C-Style Strings (Deitel, 411)

14 14 Pointers & Arrays The array name is a pointer to the first element const 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 8 cout << *pMyArray << endl; //Prints 8 Pointers and C-Style Strings (Deitel, 427)

15 15 Pointer 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 1 pMyArray++; cout << *pMyArray << endl; //Prints 2 pMyArray += 2; cout << *pMyArray << endl; //Prints 4 Pointers and C-Style Strings (Deitel, 424)

16 16 Dynamically 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 running int 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 0 delete [] myArray; Pointers and C-Style Strings

17 17 Using 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 Strings

18 18 C-Style Strings Chapter 8

19 19 C-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 them char *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) John\0 01 2 3 4

20 20 Input of C-style Strings  Strings can be input using cin char beatle[50]; cout << "Enter a Beatle: "; cin >> beatle; cout << "One of the Beatles was " << beatle;  Better method is to limit the size of the input const 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)

21 21 Functions for C-style Strings //Copy one string to another char marx[] = "Groucho"; strcpy( marx, "Karl"); //Compare two strings char marx1[] = "Harpo"; char marx2[] = "Chico"; int result = strcmp( marx1, marx2 );//0 if equal //Length of a string int length = strlen( marx1 );//returns 5 Pointers and C-Style Strings (Deitel, 446)

22 22 C++ string Class  A better, object-oriented approach #include 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)

23 23 Using a vector as a data member of a class Homework 2, Problem #3

24 24 Homework 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 list 2 Search for a customer 3 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 member

25 25 UML 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) Scope private public Data members are in the middle section. Member functions are in the bottom section. Datatype Parameter Return datatype Using a vector as a data member

26 26 UML Class Diagram class Store{ private: //The Store has-a Customer vector customers; public: void viewCustomerList(); Customer* searchForCustomer( string id ); void addCustomer( Customer &cust ); }; Composition The “has-a” relationship Store - customers : vector +viewCustomerList() +searchForCustomer(in id: string ) : Customer* +addCustomer(in cust : Customer& ) Customer - ID : string - firstName : string - lastName : string + Customer() + getID() : string + setID(in id : string ) 1 0..* Multiplicities 1 Store object has 0, 1, or many Customers Using a vector as a data member

27 27 Instantiating a vector Object #include using namespace std; int main(){ vector 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 member

28 28 Adding Data to a vector Object #include using namespace std; int main(){ vector 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 member

29 29 STL 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)

30 30 Using an STL Iterator vector 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)

31 31 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; Instantiate an iterator that can be used with a vector of chars Using a vector as a data member (Josuttis, 83–86)

32 32 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; for( pos = coll.begin(); pos != coll.end(); ++pos) Create a for loop Using a vector as a data member (Josuttis, 83–86)

33 33 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; for( pos = coll.begin(); pos != coll.end(); ++pos) Initialization Assign 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)

34 34 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; for( pos = coll.begin(); pos != coll.end(); ++pos) Condition Loop 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)

35 35 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::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)

36 36 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::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)

37 37 Bonus Lab #2 Using 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

38 38 References 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.


Download ppt "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."

Similar presentations


Ads by Google