1 / 38

Today’s Objectives

12-Jun-2006. 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

tait
Download Presentation

Today’s Objectives

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 12-Jun-2006 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

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

  3. Pointers Chapter 8

  4. Pointers and C-Style Strings (Deitel, 402) 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;

  5. Pointers and C-Style Strings (Deitel, 402) 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

  6. Pointers and C-Style Strings (Deitel, 405) 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?

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

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

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

  10. Pointers and C-Style Strings Pointer Exercises Handout

  11. Pointers and C-Style Strings (Deitel, 407) 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; }

  12. Pointers and C-Style Strings (Deitel, 407) 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? }

  13. Pointers and C-Style Strings (Deitel, 411) 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;}

  14. Pointers and C-Style Strings (Deitel, 427) 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

  15. Pointers and C-Style Strings (Deitel, 424) 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

  16. Pointers and C-Style Strings 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;

  17. Pointers and C-Style Strings 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;

  18. C-Style Strings Chapter 8

  19. J o h n \0 Pointers and C-Style Strings (Deitel, 443) 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"; 4 3 2 0 1

  20. Pointers and C-Style Strings (Deitel, 443) 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;

  21. Pointers and C-Style Strings (Deitel, 446) 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

  22. Pointers and C-Style Strings (Deitel, 884) C++ 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; } }

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

  24. Using a vector as a data member 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.

  25. Using a vector as a data member UML Class Diagram Class name (The top section) Data members are in the middle section. Member functions are in the bottom section. Datatype class Customer { private: string ID; string firstName; string lastName; public: Customer(); string getID() const { return ID; } void setID( string id ) { ID = id; } }; Customer – ID : string – firstName : string – lastName : string + Customer() + getID() : string + setID( in id : string ) Scope private public Return datatype Parameter

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

  27. Using a vector as a data member Instantiating a vector Object #include <vector> using namespace std; int main(){ vector<char> coll; Instantiate a vector object that will hold char data The object name Name of the class Template parameter – type of data the vector will hold

  28. Using a vector as a data member Adding 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.

  29. Using a vector as a data member (Josuttis, 83–86) 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

  30. Using a vector as a data member (Josuttis, 83–86) Using 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

  31. Using a vector as a data member (Josuttis, 83–86) Using 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

  32. Using a vector as a data member (Josuttis, 83–86) Using 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

  33. Using a vector as a data member (Josuttis, 83–86) Using 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) Initialization Assign a starting value to the iterator Every collection class has a begin() member function that returns an iterator representing its first element.

  34. Using a vector as a data member (Josuttis, 83–86) Using 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) 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.

  35. Using a vector as a data member (Josuttis, 83–86) Using 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.

  36. Using a vector as a data member (Josuttis, 83–86) Using 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.

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

  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.

More Related