© copyright 1992–2004 by deitel & associates, inc. and pearson education inc. all rights...
TRANSCRIPT
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Tutorial 16 – Shopping List Application: Introducing Pointers, References and Dynamic Data Structures
Outline16.1 Test-Driving the Shopping List Application16.2 Introducing Pointers16.3 Pointer Operators16.4 Passing Arguments to Functions by Reference16.5 Designing the Shopping List Application16.6 Constructing the Shopping List Application16.7 Implementing a Linked List16.8 Wrap-Up
Files• ShoppingList.cpp <- Applicaton• ShoppingItem.h, ShoppingItem.cpp <- Object• List.h, List.cpp <- Linked List
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Objectives
• In this tutorial, you will learn to:– Create and initialize pointers and references.
– Store the address of a variable in a pointer.
– Create a linked list of objects.
– Access class members using a pointer.
– Use dynamic memory management to create and delete objects.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.1 Test Driving the Shopping List Application
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.1 Test Driving the Shopping List Application (Cont.)
Figure 16.1 Running the completed Shopping List application.
Figure 16.2 Adding a new item to the shopping list.
Figure 16.3 Viewing the shopping list contents.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.1 Test Driving the Shopping List Application (Cont.)
Figure 16.4 Adding more items to the shopping list.
Figure 16.5 Viewing the updated shopping list contents.
Items displayed in reverse order of input
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Introduction to Pointers
Figure 16.6 Directly and indirectly referencing a variable.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Introduction to Pointers (Cont.)
Figure 16.8 Representation of y and yPointer in memory.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Working with Pointers
• Reference “the address of” operator (&)
– Returns the address of its operand
• Dereference “value pointed by” operator (*)
– Also known as a unary indirection operator
– Returns the “value pointed by” the name of the object to which the operand points
• The Reference and Dereference operators have complementary (or opposite) meanings. A variable referenced with & can be dereferenced with *.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Reference (the address of) Operator (&)
• The first statement assigns the value 25 to andy (a variable whose address in memory we have assumed to be 1776).
• The second statement copied to fred the content of variable andy (which is 25). This is a standard assignment operation, as you have done so many times before.
• Finally, the third statement copies to ted not the value contained in andy but a reference to it (i.e., its address, 1776). The reason is that in this third assignment operation we have preceded the identifier andy with the reference operator (&), so we were no longer referring to the value of andy but to its reference (its address in memory).
• The variable that stores the reference to another variable (like ted in the previous example) is what we call a pointer.
Source: http://www.cplusplus.com/doc/tutorial/pointers/
1 andy = 25; 2 fred = andy;3 ted = &andy;
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Dereference “value pointed by” Operator (*)
• Using a pointer we can directly access the value stored in the variable which it points to. To do this, we simply have to precede the pointer's identifier with an asterisk (*), which acts as dereference operator and that can be literally translated to "value pointed by".
1 andy = 25;2 ted = &andy;34 beth = ted; // beth equal to ted ( 1776 )5 beth = *ted; // beth equal to value pointed by ted ( 25 )
Source: http://www.cplusplus.com/doc/tutorial/pointers/
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Declaring a Variable of Type Pointer
• The declaration of pointers follows this format:
• Each points to a different data type.
= The data to which they point to do not occupy the same amount of memory (the data).
• Each pointer occupies the same amount of space in memory (the address).
1 int * number;2 char * character;3 float * greatnumber
Source: http://www.cplusplus.com/doc/tutorial/pointers/
the asterisk (*) only means that it is a pointer (it is part of its type compound specifier), and should not be confused with the dereference operator that we have seen a bit earlier, but which is also written with an asterisk (*). They are simply two different things represented with the same sign.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Declaring a Variable of Type Pointer (Cont.)
1 // my first pointer2 #include <iostream>3 using namespace std; 45 int main ()6 { 7 int firstvalue, secondvalue;8 int * mypointer;9 10 mypointer = &firstvalue;11 *mypointer = 10;12 mypointer = &secondvalue;13 *mypointer = 20;14 cout << "firstvalue is " << firstvalue << endl;15 cout << "secondvalue is " << secondvalue << endl;16 return 0;17 }
Declaring pointer variable mypointer of type integer.
Dereference “value pointed by” operator
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Pointer Initialization
• Pointers can be initialized to 0, NULL or an address
= Symbolic constant NULL defined in <iostream> as equal to 0
9 0 is the only integer that can be directly assigned to a pointer
• Initialize pointers to avoid pointing to unknown or uninitialized areas of memory
1 int number;2 int *tommy = &number;
• The behavior of this code is equivalent to:
1 int number;2 int *tommy;3 tommy = &number;
Reference “the address of” operator
Declaring pointer variable tommy of type int
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Working with References
• What is a Reference?
– It's an alias for an object - another name by which it can be called. The implementation is frequently identical to that of pointers. But don't think of references as pointers - a reference is the object.
– Strange phrases like "a reference IS the object" are used quite frequently in the C++ community. Such claims are only useful to hide the fact that C++ pointers & references are so similar that having both in the language is an unnecessary complication. In other contexts, the claims are simply false.
Source: http://yosefk.com/c++fqa/ref.html
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Then Why References?
• Both C and C++ provide pointers as a way of referring to objects indirectly.
• C++ added references as an alternative mechanism for doing what is essentially the same job.
• C++ reference types enable overloaded operators to look like built-in operators, as well as act like them.
Source: http://www.eetimes.com/discussion/programming-pointers/4024641/An-Introduction-to-References
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Declaring and Initializing a Variable of Type Reference
• A reference declaration is nearly identical to a pointer declaration, except that a reference declaration uses the & operator instead of the * operator. For example, given:
1 int i = 3;
then:
2 int *pi = &i;
• Declares pi as an object of type "pointer to int" whose initial value is the address of object i, while:
3 int &ri = i;
• Declares ri as an object of type "reference to int" referring to i.
• The ampersand (&), as used in line 3 is not the reference operator (although both use the same sign: &). Remember, they are two different functions of one sign.
Source: http://www.eetimes.com/discussion/programming-pointers/4024641/An-Introduction-to-References
Reference “the address of” operator
Declaring Reference variable ri of type integer.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Declaring and Initializing a Variable of Type Reference
• Nomenclature
– Initializing a reference to refer to an object is often described as "binding the reference to the object."
– many programmers pronounce "int *" as "int star," they usually pronounce "int &" as "int ref."
Source: http://www.eetimes.com/discussion/programming-pointers/4024641/An-Introduction-to-References
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
The Difference between Pointer and Reference Variables
• You can use a reference as if it were a value: myRef.myData,versus myPtr->myData, which is equivalent to ( *myPtr).myData (in this sense myRef behaves like (*myPtr)).
• A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.
– In Fact, a reference must be initialized to point to an object - otherwise, the code won't compile.
– After the initialization, you can't make a pointer, point to any number of objects.
• A pointer can point to NULL while reference can never point to NULL
– In fact, a wide class of bugs comes from accessing dangling references - references to objects which were already destroyed.
Source: http://stackoverflow.com/questions/57483/difference-between-pointer-variable-and-reference-variable-in-c
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
The Difference between Pointer and Reference Variables
• You can't take the address of a reference (it is bound to the object) like you can with pointers (forming a pointer to a pointer). We will see an example of this when we study linked lists.
• There's no "reference arithmetics"
– but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5.
Source: http://stackoverflow.com/questions/57483/difference-between-pointer-variable-and-reference-variable-in-c
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
When to use a Reference or Pointer
• Pointers can do almost everything that references can do, but they can lead to expressions that don't look right.
• On the other hand, references have some restrictions that make them less convenient than pointers for implementing algorithms and data structures.
• As a general rule,
– Use pointers to implement algorithms and data structures.
– Use references in function parameters and return types to define attractive interfaces. We look at Passing Arguments to Functions by Reference or Pointer in the next section.
Source: http://www.eetimes.com/discussion/programming-pointers/4024641/An-Introduction-to-References
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.4 Passing Arguments to Functions by Reference or Pointer
• There two (2) ways to perform a pass-by-reference
1. pass-by-reference with reference (&) argument
2. pass-by-reference with pointer (*) argument
Review
A “parameter” is the thing used to define a method or function while an “argument” is the thing you use to call a method or function.
Parameter:
void mySubroutine (int N){ … } N is a parameter
Argument:
int X;X = 10;mySubroutine(X); X is an argument
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.4 Passing Arguments to Functions by Reference
• To indicate that a function passes parameters by reference, follow the variable type with an ampersand (&) in the function prototype
Figure 16.9 Declaring a function that declares a reference parameter.
Declaring a function that declares an int reference parameter
Figure 16.10 Passing an argument by reference using a reference argument.
Using a variable name to pass-by-reference using a reference argument
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.4 Passing Arguments to Functions by Reference (Cont.)
• Passing variables by reference allows the called function to directly modify the original variable in the caller. In this example the variable input.
Figure 16.11 Defining a function that declares a reference parameter.
Incrementing the reference parameter
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.4 Passing Arguments to Functions by Reference (Cont.)
Figure 16.12 Output demonstrating the value of input before and after passing a value by reference with a reference argument.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.4 Passing Arguments to Functions by Pointer
• To pass a function parameter as a pointer, follow the parameter’s type in the function prototype with an asterisk (*)
• The asterisk (*), as used here is not the dereference operator (although both use the same sign: *). Remember, they are two different functions of one sign.
Figure 16.13 Declaring a function that declares a pointer parameter.
Declaring a function that declares an int pointer parameter
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.4 Passing Arguments to Functions by Pointer (Cont.)
Figure 16.14 Passing a variable by reference using a pointer argument.
Using “the address of” operator to pass-by-reference using a pointer
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.4 Passing Arguments to Functions by Pointer (Cont.)
• Always use parenthesis to make order of operation clear.
• The asterisk (*), as used in line 53 is not the dereference operator (although both use the same sign: *). Remember, they are two different functions of one sign.
Figure 16.15 Defining a function that declares a pointer argument.
Increment the value
Declaring Pointer variable countPointer of type integer.
Dereference “value pointed by” operator
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.4 Passing Arguments to Functions by Pointer (Cont.)
Figure 16.16 Output showing input before and after passing it by reference using reference and pointer arguments.
Recap
Using a reference as a function parameter provides an attractive interface, while using a pointer parameter explicitly shows that a link exists between the parameter and the argument.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.4 Passing Arguments to Functions by Reference (Cont.)
• Array names are actually pointers pointing to element zero in the array
– arrayName is equivalent to &arrayName[ 0 ]
– This is why arrays are always pass-by-reference as a pointer.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Display a menu containing options for adding a new item to the list,displaying the shopping list and exiting the application
Prompt the user for and input the menu selectionIf the user chose to add a new item to the list
Prompt the user for and input the name and quantity of the itemCreate a new ShoppingItem objectAdd the new ShoppingItem to the linked List of ShoppingItems
If the user chose to display the shopping listFor each item in the list
Display the item’s name and quantityIf the user chose to exit
Delete each ShoppingItem and exit the application
Figure 16.17 Pseudocode for the ShoppingList application.
16.5 Designing the Shopping List Application
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.5 Designing the Shopping List Application (Cont.)
Figure 16.18 ShoppingItem class definition.
ShoppingItem constructor
Get and set functions
Member function that displays ShoppingItem information
Defining variables that represent an item’s name and quantity
Link data member
Pointer variable next of type ShoppingItem
Declares a shoppingItem pointer parameter
Next Object in a linked list
Declares a string reference parameter
Object’s name
Quantity
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.5 Designing the Shopping List Application (Cont.)
• A self-referential class contains a pointer to an object of the same class
• Not setting the link in the last node of a linked data structure to NULL (0) is a (possibly fatal) logic error.
Figure 16.19 Two self-referential class objects linked together.
Self-referential class objects linked together to form a list
Pointer to the first self-referential class object in the list
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.5 Designing the Shopping List Application (Cont.)
• Linked list
– Collection of linked nodes
– Length is dynamic
• Can increase and decrease as necessary
– Singly-linked list has one link per node
Figure 16.20 Graphical representation of a linked list.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.6 Constructing the Shopping List Application
Figure 16.21 Including the ShoppingItem and List class definitions.
Including the ShoppingItem.h and List.h header files
ShoppingList C++ application
Figure 16.22 Defining variables to store user input.
Defining variables to store user input
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.6 Constructing the Shopping List Application (Cont.)
• Invoking the List class default constructor
Figure 16.23 Creating a List object.
Creating a List object
C++ is case sensitive so shoppingList the list is not the same as ShoppingList the application
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Menu Selection Case 1
Figure 16.2 Adding a new item to the shopping list.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Menu Selection Case 1Figure 16.24 Prompting the user for and inputting the item’s name and quantity.
The ignore function removes one character from the input stream
Prompting the user for and inputting the item’s name and quantity
Figure 16.25 Adding a new ShoppingItem object to ShoppingList.
Add a new ShoppingItem to the linked list
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Menu Selection Case 2
Figure 16.26 Displaying the name and quantity for each ShoppingItem in the linked list.
Displaying the contents of the shopping list
Figure 16.3 Viewing the shopping list contents.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Menu Selection Case 3
• Applications should delete any dynamic memory allocated during run-time.
Figure 16.27 Deleting each ShoppingItem object from the ShoppingList.
Deleting all ShoppingItem objects
Figure 16.38 Terminating the Shopping List application.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Figure 16.28 List class definition.
16.7 Implementing a Linked List
List constructor
Declaring set and get functions for the pointer to the first item in the list
Declaring functions to manipulate the linked list of ShoppingItems
Defining a pointer to the first item in the linked list
List header file
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.7 Implementing a Linked List (Cont.)
• Keyword this– Inside a member function, you can explicitly refer to the object of that
class on which the function was called with the keyword this
• Arrow operator (->)– Shorthand notation for use with pointers– myObject->myData is equivalent to ( *myObject ).myData
Figure 16.29 List constructor definition.
Initializing the firstItem variable as a null pointer
List C++ object
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Figure 16.30 Graphical representation of inserting an item at the front of a linked list.
16.7 Implementing a Linked List (Cont.)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.7 Implementing a Linked List (Cont.)
• Dynamic memory allocation
– Technique of obtaining memory during execution time
– Allocated memory can be released so that it can be reused later
• new operator
– Takes as an argument the type of object being created
– Returns a pointer to newly created object
Figure 16.31 Creating a ShoppingItem object in the addItem function.
Creating a ShoppingItem using the new operator
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.7 Implementing a Linked List (Cont.)
• Assign NULL (zero) to the link member of a new node
– Uninitialized pointers often lead to dangerous runtime errors
Figure 16.32 Updating pointers when adding an item to the front of a linked list.
Updating the new ShoppingItem’s nextItem variable and the List’s firstItem variable
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.7 Implementing a Linked List (Cont.)
Figure 16.33 Defining the displayList function.
Creating a pointer to the first item in the linked list
Displaying a header
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.7 Implementing a Linked List (Cont.)
Figure 16.34 Displaying each ShoppingItem’s name and quantity.
Displaying the name and quantity for each ShoppingItem
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.7 Implementing a Linked List (Cont.)
• Deallocating memory
– Not releasing dynamically allocated memory when it is no longer needed can cause the system to run out of memory prematurely
• delete operator
– Runs the destructor and deallocates the memory allocated by the new operator
– Returns memory to the system
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.7 Implementing a Linked List (Cont.)
Figure 16.35 Defining the deleteList function.
Setting currentItem so that it points to the first item in the linked list
Repeat until reaching the end of the list
Variable currentItem is a pointer to type ShoppingItem
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.7 Implementing a Linked List (Cont.)
• Destructors
– Functions that run just before an object’s memory is released
Figure 16.36 Deleting each ShoppingItem in the linked list.
Store a temporary copy of the pointer to the next ShoppingItem
Delete the ShoppingItem to which currentItem points
Move to the next item in the List
Temporary variable nextItem is a pointer to type ShoppingItem
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.7 Implementing a Linked List (Cont.)
Figure 16.37 Shopping List application after entering several items.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
16.7 Implementing a Linked List (Cont.)
Figure 16.38 Terminating the Shopping List application.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
1 // Tutorial 16: List.h
2 // List class stores pointers to the first item in
3 // the linked list and manages the linked list.
4 #ifndef LIST_H
5 #define LIST_H
6
7 #include "ShoppingItem.h" // ShoppingItem class definition
8
9 using namespace std; // for accessing C++ Standard Library members
10
11 class List {
12
13 public:
14 List(); // constructor
15
List.h (1 of 2)
List constructor
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
11
17 void setFirstItem( ShoppingItem * );
18 ShoppingItem *getFirstItem();
19
20 // utility functions
21 void addItem( string, int ); // add an item to front of the list
22 void displayList(); // display each item in the list
23 void deleteList(); // delete each item in the list
24
25 private:
26 ShoppingItem *firstItem; // pointer to the first item in the list
27
28 }; // end class List
29
30 #endif // LIST_H
List.h (2 of 2)Get and set functions for the pointer to the first item in the list
Declaring functions to manipulate the linked list of ShoppingItems
Pointer to the first item in the linked list
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
1 // Tutorial 16: List.cpp
2 // Class List member-function definitions.
3 #include <iostream> // required to perform C++-style stream I/O
4
5 using namespace std; // for accessing C++ Standard Library members
6
7 #include "List.h" // List class definition
8
9 // List constructor
10 List::List()
11 {
12 // initialize firstItem and lastItem as pointers to nothing
13 setFirstItem( 0 );
14
15 } // end constructor
16
List.cpp (1 of 5)
Initialize the firstItem as a null pointer
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
17 // set the pointer for the first item in the list
18 void List::setFirstItem( ShoppingItem *newFirstItem )
19 {
20 firstItem = newFirstItem;
21 } // end function setFirstItem
22
23 // return a pointer to the first item in the list
24 ShoppingItem *List::getFirstItem()
25 {
26 return firstItem;
27 } // end function getFirstItem
28
List.cpp (2 of 5)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
29 // add an item to the front of the list
30 void List::addItem( string itemName, int quantity )
31 {
32 // create the new ShoppingItem
33 ShoppingItem *nextItem =
34 new ShoppingItem( itemName, quantity, 0 );
35
36 // update pointer to the next item
37 newItem->setNextItem( getFirstItem() );
38 setFirstItem( newItem ); // add new item to the front of the list
39
40 } // end function addItem
41
List.cpp (3 of 5)
Update the firstItem to point to the new ShoppingItem
Update the appropriate pointers to add the new item to the list
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
42 // display each item in the list
43 void List::displayList()
44 {
45 // get a pointer to the head of the list
46 ShoppingItem *currentItem = getFirstItem();
47
48 // display a header
49 cout << "\nShopping List" << endl;
50 cout << "-------------" << endl;
51
52 // display information for each item
53 while ( currentItem != 0 )
54 {
55 currentItem->display(); // display name and quantity
56 currentItem = currentItem->getNextItem(); // move to next item
57 } // end while
58
59 } // end function displayList
60
List.cpp (4 of 5)
Create a pointer to the first item in the linked list
Display a header
Display the name and quantity for each ShoppingItem
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
61 // delete each item in the list
62 void List::deleteList()
63 {
64 // get a pointer to the head of the list
65 ShoppingItem *currentItem = getFirstItem();
66
67 // delete each item
68 while ( currentItem != 0 )
69 {
70 // store a pointer to the next item
71 ShoppingItem *nextItem = currentItem->getNextItem();
72 cout << "\nMemory being released for: “
73 << currentItem->getName() << endl;
74 delete currentItem; // delete the current item
75
76 // place a pointer to the next item in currentItem
77 currentItem = nextItem;
78 } // end while
79
80 } // end function deleteList
List.cpp (5 of 5)
Create a pointer to the first item in the linked list
Delete each ShoppingItem in the linked list
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
1 // Tutorial 16: ShoppingItem.h
2 // ShoppingItem class stores item name, quantity and a pointer to
3 // the next item in the list.
4 #ifndef SHOPPINGITEM_H
5 #define SHOPPINGITEM_H
6
7 #include <string> // required to access string functions
8
9 using namespace std; // for accessing C++ Standard Library members
10
11 class ShoppingItem {
12
13 public:
14 ShoppingItem( string & , int, ShoppingItem * ); // constructor
15
16 // get and set functions for the item name
17 void setName( string & );
18 string getName();
19
ShoppingItem.h (1 of 2)
ShoppingItem constructor
Get and set functions
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
20 // get and set functions for the item quantity
21 void setQuantity( int );
22 int getQuantity();
23
24 // get and set functions for the pointer to the next ShoppingItem
25 void setNextItem( ShoppingItem * );
26 ShoppingItem *getNextItem();
27
28 void display(); // function to display the name and quantity
29
30 private:
31 string name; // item name
32 int quantity; // item quantity
33
34 // pointer to the next ShoppingItem in the list
35 ShoppingItem *next;
36
37 }; // end class ShoppingItem
38
39 #endif // SHOPPINGITEM_H
ShoppingItem.h (2 of 2)
Member function that displays ShoppingItem information
Defining variables that represent an item name and quantity
Link data member
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
1 // Tutorial 16: ShoppingItem.cpp
2 // Class ShoppingItem member-function definitions.
3 #include <iostream> // required to perform C++-style stream I/O
4 #include "ShoppingItem.h" // ShoppingItem class definition
5
6 using namespace std; // for accessing C++ Standard Library members
7
8 // constructor
9 ShoppingItem::ShoppingItem( string &itemName, int itemQuantity,
10 ShoppingItem *nextPointer )
11 {
12 // initialize data members
13 setName( itemName ); // set the name
14 setQuantity( itemQuantity ); // set the quantity
15 setNextItem( nextPointer ); // set pointer to the next item
16
17 } // end constructor
18
19 // set the item's name
20 void ShoppingItem::setName( string &itemName )
21 {
22 name = itemName;
23 } // end function setName
24
ShoppingItem.cpp (1 of 4)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
25 // return a copy of the item's name so that changes made to
26 // the returned value do not affect the object's name member
27 string ShoppingItem::getName()
28 {
29 return name;
30
31 } // end function getName
32
33 // set the quantity for this item
34 void ShoppingItem::setQuantity( int itemQuantity )
35 {
36 if ( itemQuantity < 0 )
37 {
38 quantity = 0;
39 } // end if
40 else
41 {
42 quantity = itemQuantity;
43 } // end else
44
45 } // end function setQuantity
46
ShoppingItem.cpp (2 of 4)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
47 // return the item's quantity
48 int ShoppingItem::getQuantity()
49 {
50 return quantity;
51
52 } // end function getQuantity
53
54 // set the pointer to the next ShoppingItem in the list
55 void ShoppingItem::setNextItem( ShoppingItem *nextPointer )
56 {
57 next = nextPointer;
58
59 } // end function setNextItem
60
ShoppingItem.cpp (3 of 4)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
61 // return the pointer to the next item
62 ShoppingItem *ShoppingItem::getNextItem()
63 {
64 return next;
65
66 } // end function getNextItem
67
68 // return the pointer to the next item
69 void ShoppingItem::display()
70 {
71 cout << "\nName: " << getName() << endl;
72 cout << "Quantity: " << getQuantity() << endl;
73
74 } // end function display
ShoppingItem.cpp (4 of 4)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
1 // Tutorial 16: ShoppingList.cpp
2 // Enables users to add items to, remove items from and view items in
3 // a shopping list.
4 #include <iostream> // required to perform C++-style stream I/O
5 #include <iomanip> // required for parameterized stream manipulators
6
7 using namespace std; // for accessing C++ Standard Library members
8
9 #include "ShoppingItem.h" // ShoppingItem class definition
10 #include "List.h" // List class definition
11
12 int displayMenu(); // function prototype
13
14 // function main begins program execution
15 int main()
16 {
17 int selection = 0; // stores the user's menu selection
18 string itemName; // stores the item name
19 int itemQuantity; // stores the item quantity
20 List shoppingList; // stores a list of shopping items
21
ShoppingList.cpp (1 of 4)
Include the ShoppingItem.h and List.h header files
Define variables to store user input
Create a List object
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
22 while ( selection != 3 )
23 {
24 selection = displayMenu();
25
26 switch ( selection )
27 {
28 // enter item information
29 case 1:
30 cin.ignore(); // remove newline from cin
31
32 // prompt user for and input item name and quantity
33 cout << "\nEnter item name: ";
34 getline( cin, itemName ); // get name
35
36 cout << "Enter quantity: ";
37 cin >> itemQuantity; // get quantity
38
39 // add new shopping item to the list
40 shoppingList.addItem( itemName, itemQuantity )
41
42 break;
43
ShoppingList.cpp (2 of 4)
Remove the newline from the input stream
Prompt the user for and input the item’s name and quantity
Add a new ShoppingItem to the linked list
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
44 // view all items in the list
45 case 2:
46 shoppingList.displayList(); // display each item
47
48 break;
49
50 // exit
51 case 3:
52 shoppingList.deleteList(); // delete each object
53 cout << "\n"; // display newline for readability
54 break;
55
56 default:
57 cout << "Error: Enter a valid menu selection";
58
59 } // end switch
60
61 } // end while
62
63 return 0; // indicate that program ended successfully
64
65 } // end function main
66
ShoppingList.cpp (3 of 4)
Display the contents of the shopping list
Delete all ShoppingItem objects in the linked list
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
67 // displays a menu and returns the selected menu option number
68 int displayMenu()
69 {
70 int selection = 0; // stores the menu option number
71
72 // display the menu
73 cout << "\nSelect one of the following options" << endl;
74 cout << "1 - Enter new item" << endl;
75 cout << "2 - Display list" << endl;
76 cout << "3 - Exit the application" << endl;
77 cout << "Enter selection: ";
78 cin >> selection;
79
80 return selection; // return the selection
81
82 } // end function displayMenu
ShoppingList.cpp (4 of 4)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Lab and Homework Assignment
• Tutorial 16 − Shopping List Application. Turn in annotated source file with your own comments for Exercise 16.11 or Exercise 16.16 if you finish the design challenge.
• Answer and Turn-in Tutorial 16 Questions 16.1 to 16.10. Note: The author defines “synonym” on page 371. Always write the question followed by the answer. Remember to highlight the answer.
• Exercises 16.11 and 16.16. For both exercises start from your completed Tutorial.
• Due next Wednesday
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Lecture 2 – Introduction to Linked Lists
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Lecture 3 – Data Operations on Linked List
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Lecture 3 – Data Operations on Linked List