Presentation is loading. Please wait.

Presentation is loading. Please wait.

CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class.

Similar presentations


Presentation on theme: "CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class."— Presentation transcript:

1 CHAPTER 13 CLASSES AND DATA ABSTRACTION

2 In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class  Explore how classes are implemented  Examine constructors and destructors  Learn about the abstract data type (ADT)  Explore how classes are used to implement ADT  Learn about information hiding  Explore how information hiding is implemented in C++

3 CLASSES  A class is a collection of a fixed number of components.  The components of a class are called members of the class. The general syntax of defining a class is: class classIdentifier { classMemberList };  A member of a class can either be a variable (that is, to store some data) or a function.

4  If a member of a class is a variable, you declare it just like any other variable. Also, in the definition of the class, you cannot initialize a variable when you declare it.  If a member of a class is a function, you typically use the function prototype to define that member.  If a member of a class is a function, it can (directly) access any member of the class—data members and function members. That is, when you write the definition of the member function, you can directly access any data member of the class without passing it as a parameter. The only obvious condition is that you must declare an identifier before you can use it.  In C++, class is a reserved word and it only defines a data type, no memory is allocated.  The semicolon after the right brace is part of the syntax.  A missing semicolon, therefore, will result in a syntax error.

5  The members of a class are classified into three categories: private, public, and protected. This chapter mainly discusses the first two types—that is, private and public.  Following are some facts about public and private members of a class:  By default, all members of a class are private.  If a member of a class is private, you cannot access it outside the class.  A public member is accessible outside the class.  To make a member of a class public, you use the label public with a colon.  In C++, private, protected, and public are reserved words.

6  Define a class, clockType, to implement the time of day in a program.  Time is represented as a set of three integers: one to represent the hours, one to represent the minutes, and one to represent the seconds.  Perform the following operations on the time: 1. Set the time. 2. Return the time. 3. Print the time. 4. Increment the time by one second. 5. Increment the time by one minute. 6. Increment the time by one hour. 7. Compare the two times for equality.

7

8  Some members of the class clockType will be private ; others will be public.  Any member that needs to be accessed outside the class is declared public ; any member that should not be accessed directly by the user should be declared private.  The user should be able to set the time and print the time. Therefore, the members that set the time and print the time should be declared public.

9 class clockType { public: void setTime(int, int, int); void getTime(int&, int&, int&); void printTime() const; void incrementSeconds(); void incrementMinutes(); void incrementHours(); bool equalTime(const clockType& otherTime) const; private: int hr; int min; int sec; };

10  The class clockType has seven function members: setTime, getTime, printTime, incrementSeconds, incrementMinutes, incrementHours, and equalTime.  It has three data members: hr, min, and sec.  The three data members— hr, min, and sec, are private to the class and cannot be accessed outside the class.  The seven function members— setTime, getTime, printTime, incrementSeconds, incrementMinutes, incrementHours, and equalTime —can directly access the data members ( hr, min, and sec ).  In the function equalTime, the parameter otherClock is a constant reference parameter. That is, in a call to the function equalTime, the parameter otherClock receives the address of the actual parameter, but otherClock cannot modify the value of the actual parameter.  The word const at the end of the member functions printTime and equalTime specifies that these functions cannot modify the data members of a variable of the type clockType.

11 Variable (Object) Declaration  Once a class is defined, you can declare variables of that type.  In C++ terminology, a class variable is called a class object or class instance.  To become familiar with this terminology, we will use the term class object, or simply object, for a class variable.  The syntax for declaring a class object is the same as that for declaring any other variable. clockTypemyClock; clockTypeyourClock;

12

13 Accessing Class Members  Once an object is declared, it can access the public members of a class.  The general syntax to access the member of a class is classVariableName.memberName  In C++, the dot,. (period), is an operator called the member access operator.

14 Example 13-1 myClock.setTime(5,2,30); myClock.printTime(); yourClock.setTime(x,y,z); //Assume x, y, and //z are variables of the type int if(myClock.equalTime(yourClock)). myClock.hr = 10; //illegal myClock.min = yourClock.min; //illegal

15 Built-in Operations on Classes  Most of C++’s built-in operations do not apply to classes.  You cannot use arithmetic operators to perform arithmetic operations on class objects (unless they are overloaded).  For example, you cannot use the operator + to add two class objects of, say, the type clockType.  Also, you cannot use relational operators to compare two class objects for equality.  The two built-in operations that are valid for class objects are member access (. ) and assignment ( = ).

16 The Assignment Operator and Classes Suppose that myClock and yourClock are variables of the type clockType.

17 The statement myClock = yourClock; copies the value of yourClock into myClock a.the value of yourClock.hr is copied into myClock.hr, b.the value of yourClock.min is copied into myClock.min c.the value of yourClock.sec is copied into myClock.sec

18 Class Scope A class variable has the same scope as other variables. A member of a class is local to the class. We access a class member outside the class by using class variable name and the member selection operator (.).

19 Functions and Classes  Class objects can be passed as parameters to functions and returned as function values.  As parameters to functions, classes can be passed either by value or by reference.  If a class object is passed by value, the contents of the data members of the actual parameter are copied into the corresponding data members of the formal parameter.

20 Reference Parameters and Class Objects (Variables)  As a parameter, a class object can be passed by value.  If a variable is passed by value, the corresponding formal parameter receives a copy of the data of the variable. This operation might require, in addition to a large amount of storage space, a considerable amount of computer time to copy the value of the actual parameter into the formal parameter.  If a variable is passed by reference, the formal parameter receives only the address of the actual parameter. Therefore, an efficient way to pass a variable as a parameter is by reference.  If a variable is passed by reference, then when the formal parameter changes, the actual parameter also changes.  In C++, you can pass a variable by reference and still prevent the function from changing its value, by using the keyword const in the formal parameter declaration.

21 void testTime(const clockType& otherClock) { clockType dClock;... }

22 Implementation of Member Functions In the heading of the function definition, the name of the function is the name of the class followed by the scope resolution operator followed by the function name. void clockType::setTime(int hours, int minutes, int seconds) { if(0 <= hours && hours < 24) hr = hours; else hr = 0; if(0 <= minutes && minutes < 60) min = minutes; else min = 0; if(0 <= seconds && seconds < 60) sec = seconds; else sec = 0; }

23 The member function setTime is a void function and has three parameters. Therefore, 1. A call to this function is a standalone statement. 2. We must use three parameters in a call to this function. 3. Since setTime is a member of the class clockType, it can directly access the data members hr, min, and sec as shown in the definition of setTime. Suppose that myClock is a variable of the type clockType

24 myClock.setTime(3,48,52);

25 void clockType::printTime() const { if(hr < 10) cout<<"0"; cout<<hr<<":"; if(min < 10) cout<<"0"; cout<<min<<":"; if(sec < 10) cout<<"0"; cout<<sec; } void clockType::getTime(int& hours, int& minutes, int& seconds) { hours = hr; minutes = min; seconds = sec; }

26 void clockType::incrementHours() { hr++; if(hr > 23) hr = 0; } void clockType::incrementMinutes() { min++; if(min > 59) { min = 0; incrementHours(); } void clockType::incrementSeconds() { sec++; if(sec > 59) { sec = 0; incrementMinutes(); }

27 bool clockType::equalTime(const clockType& otherClock) const { return (hr == otherClock.hr && min == otherClock.min && sec == otherClock.sec); } Suppose that

28 if(myClock.equalTime(yourClock)).

29 //Program that uses the class clockType int main() { clockType myClock; clockType yourClock; int hours; int minutes; int seconds; myClock.setTime(5,4,30);//Line 1 cout<<"Line 2: myClock: ";//Line 2 myClock.printTime();//Line 3 cout<<endl;//Line 4 cout<<"Line 5: yourClock: ";//Line 5 yourClock.printTime();//Line 6 cout<<endl;//Line 7 yourClock.setTime(5,45,16);//Line 8 cout<<"Line 9: After setting - yourClock: ";//Line 9 yourClock.printTime();//Line 10 cout<<endl;//Line 11

30 if(myClock.equalTime(yourClock))//Line 12 cout<<"Line 13: Both times are equal." <<endl; //Line 13 else//Line 14 cout<<"Line 15: The two times are not equal" <<endl; //Line 15 cout<<"Line 16: Enter hours, minutes, and " <<"seconds: ";//Line 16 cin>>hours>>minutes>>seconds;//Line 17 cout<<endl;//Line 18 myClock.setTime(hours,minutes,seconds);//Line 19 cout<<"Line 20: New myClock: ";//Line 20 myClock.printTime();//Line 21 cout<<endl;//Line 22 myClock.incrementSeconds();//Line 23 cout<<"Line 24: After incrementing the clock by " <<"one second, myClock: ";//Line 24 myClock.printTime();//Line 25 cout<<endl;//Line 26

31 return 0; }//end main Output: The user input is in red. Line 2: myClock: 05:04:30 Line 5: yourClock: (The value of yourClock is undefined here). Line 9: After setting - yourClock: 05:45:16 Line 15: The two times are not equal Line 16: Enter hours, minutes, and seconds: 5 23 59 Line 20: New myClock: 05:23:59 Line 24: After incrementing the time by one second, myClock: 05:24:00

32 //The complete program listing of the program that // defines and uses class clockType #include using namespace std; class clockType { public: void setTime(int, int, int); void getTime(int&, int&, int&); void printTime() const; void incrementSeconds(); void incrementMinutes(); void incrementHours(); bool equalTime(const clockType&) const; private: int hr; int min; int sec; };

33 int main() { clockType myClock; clockType yourClock; int hours; int minutes; int seconds; myClock.setTime(5,4,30);//Line 1 cout<<"Line 2: myClock: ";//Line 2 myClock.printTime();//Line 3 cout<<endl;//Line 4 cout<<"Line 5: yourClock: ";//Line 5 yourClock.printTime();//Line 6 cout<<endl;//Line 7 yourClock.setTime(5,45,16);//Line 8 cout<<"Line 9: After setting - yourClock: ";//Line 9 yourClock.printTime();//Line 10 cout<<endl;//Line 11

34 if(myClock.equalTime(yourClock))//Line 12 cout<<"Line 13: Both times are equal." <<endl; //Line 13 else//Line 14 cout<<"Line 15: The two times are not equal" <<endl; //Line 15 cout<<"Line 16: Enter hours, minutes, and " <<"seconds: ";//Line 16 cin>>hours>>minutes>>seconds;//Line 17 cout<<endl;//Line 18 myClock.setTime(hours,minutes,seconds);//Line 19 cout<<"Line 20: New myClock: ";//Line 20 myClock.printTime();//Line 21 cout<<endl;//Line 22 myClock.incrementSeconds();//Line 23 cout<<"Line 24: After incrementing the clock by " <<"one second, myClock: ";//Line 24 myClock.printTime();//Line 25 cout<<endl;//Line 26

35 return 0; }//end main void clockType::setTime(int hours, int minutes, int seconds) { if(0 <= hours && hours < 24) hr = hours; else hr = 0; if(0 <= minutes && minutes < 60) min = minutes; else min = 0; if(0 <= seconds && seconds < 60) sec = seconds; else sec = 0; }

36 void clockType::getTime(int& hours, int& minutes, int& seconds) { hours = hr; minutes = min; seconds = sec; } void clockType::incrementHours() { hr++; if(hr > 23) hr = 0; } void clockType::incrementMinutes() { min++; if(min > 59) { min = 0; incrementHours(); }

37 void clockType::incrementSeconds() { sec++; if(sec > 59) { sec = 0; incrementMinutes(); } void clockType::printTime() const { if(hr < 10) cout<<"0"; cout<<hr<<":"; if(min < 10) cout<<"0"; cout<<min<<":"; if(sec < 10) cout<<"0"; cout<<sec; }

38 bool clockType::equalTime(const clockType& otherClock) const { return (hr == otherClock.hr && min == otherClock.min && sec == otherClock.sec); } Sample Run In this sample run, the user input is in red. Line 2: myClock: 05:04:30 Line 5: yourClock: 0-858993460:0-858993460:0- 858993460 Line 9: After setting - yourClock: 05:45:16 Line 15: The two times are not equal Line 16: Enter hours, minutes, and seconds: 5 23 59 Line 20: New myClock: 05:23:59 Line 24: After incrementing the time by one second, myClock: 05:24:00

39 Order of Public and Private Members of a Class Example 13-3 class clockType { public: void setTime(int, int, int); void getTime(int&, int&, int&); void printTime() const; void incrementSeconds(); void incrementMinutes(); void incrementHours(); bool equalTime(const clockType&) const; private: int hr; int min; int sec; };

40 Example 13-4 class clockType { private: int hr; int min; int sec; public: void setTime(int, int, int); void getTime(int&, int&, int&); void printTime() const; void incrementSeconds(); void incrementMinutes(); void incrementHours(); bool equalTime(const clockType&) const; };

41 Example 13-5 class clockType { int hr; int min; int sec; public: void setTime(int, int, int); void getTime(int&, int&, int&); void printTime() const; void incrementSeconds(); void incrementMinutes(); void incrementHours(); bool equalTime(const clockType&) const; };

42 Constructors and Destructors Constructors We can guarantee the initialization of the data members of a class by using constructors. There are two types of constructors: with parameters and without parameters. The constructor without parameters is called the default constructor.

43 1. The name of a constructor is the same as the name of the class. 2. A constructor, even though it is a function, has no type. That is, it is neither a value-returning function nor a void function. 3. A class can have more than one constructor. However, all constructors of a class have the same name. 4. If a class has more than one constructor, they must have different sets of parameters. 5. Constructors are automatically executed when a class variable enters its scope. Since they have no types, they cannot be called like other functions. 6. Which constructor executes depends on the type of values passed to the class variable when the class variable is declared.

44 class clockType { public: void setTime(int, int, int); void getTime(int&, int&, int&); void printTime() const; void incrementSeconds(); void incrementMinutes(); void incrementHours(); bool equalTime(const clockType&) const; clockType(int, int, int); //constructor with parameters clockType(); //default constructor private: int hr; int min; int sec; };

45 clockType::clockType(int hours, int minutes, int seconds) { if(0 <= hours && hours < 24) hr = hours; else hr = 0; if(0 <= minutes && minutes < 60) min = minutes; else min = 0; if(0 <= seconds && seconds < 60) sec = seconds; else sec = 0; } clockType::clockType() //default constructor { hr = 0; min = 0; sec = 0; }

46 Invoking a Constructor A constructor is automatically executed when a class variable is declared. A class might have more than one constructor, including the default constructor.

47 Invoking the default Constructor The syntax to invoke the default constructor is: className classVariableName; The statement clockType yourClock; declares yourClock to be a variable of the type clockType. In this case, the default constructor is executed and the data members of yourClock will be initialized to zero.

48 Invoking a Constructor with Parameters The syntax to invoke a constructor with parameter is: className classVariableName(argument1, argument2,... ); where argument1, argument2, etc. is either a variable of an expression. 1. The number of arguments and their type should match with the formal parameters (in the order given) of one of the constructors. 2. If the type of the arguments do not match with the formal parameters of any constructor (in the order given), C++ will use type conversion and look for the best match. For example, an integer value might be converted to a floating-point value with zero decimal part. An ambiguity will result in a compile time error.

49 Consider the statement. clockType myClock(5,12,40); This statement declares a class variable myClock. In this case, the constructor with parameters of the class clockType will be executed and the three data members of the variable myClock will be set to 5, 12, and 40.

50 Example 13-6 class testClass { public: void print();//Line a testClass();//Line b testClass(int, int);//Line c testClass(int, double, int);//Line d testClass(double, char);//Line e private: int x; int y; double z; char ch; }; void testClass::print() { cout<<"x = "<<x<<", y = "<<y<<", z = "<<z <<", ch = "<<ch<<endl; }

51 testClass::testClass()//default constructor { x = 0; y = 0; z = 0; ch = '*'; } testClass::testClass(int a, int b) { x = a; y = b; z = 0; ch = '*'; } testClass::testClass(int a, double c, int b) { x = a; y = b; z = c; ch = '*'; }

52 testClass::testClass(double c, char d) { x = 0; y = 0; z = c; ch = d; } testClass one;//Line 1 testClass two(5,6);//Line 2 testClass three(5,4.5,7);//Line 3 testClass four(4,9,12);//Line 4 testClass five(3.4,'D');//Line 5

53 For the object one (declared at Line 1 ) the default constructor (at Line b ) will be executed. For the object two (declared at Line 2), the constructor with int parameters at Line c will be executed. To initialize the data members of the object three the constructor at Line d will be executed. In the case of object four the constructor at Line d will be executed. To initialize the data members of the variable five, the constructor at Line e will be executed.

54 int main() { testClass one;//Line 1 testClass two(5,6);//Line 2 testClass three(5,4.5,7);//Line 3 testClass four(4,9,12);//Line 4 testClass five(3.4,'D');//Line 5 one.print();//Line 6; output one two.print();//Line 7; output two three.print();//Line 8; output three four.print();//Line 9; output four five.print();//Line 10; output five return 0; } Output x = 0, y = 0, z = 0, ch = * x = 5, y = 6, z = 0, ch = * x = 5, y = 7, z = 4.5, ch = * x = 4, y = 12, z = 9, ch = * x = 0, y = 0, z = 3.4, ch = D

55  A constructor that has no parameters, or has all default parameters, is called the default constructor. Example 13-7 class testClass { public: void print(); testClass(int = 0, double = 0.0, int = 0, char = '*'); private: int x; int y; double z; char ch; };

56 testClass::testClass(int a, double c, int b, char d) { x = a; y = b; z = c; ch = d; } testClass one; testClass two(5,0.0,6); testClass three(5,4.5,7); testClass four(4,9,12); testClass five(0,3.4,0,'D');

57 Arrays of Class Objects (Variables) and Constructors  If a class has constructors and you declare an array of class objects, the class must have the default constructor.  The default constructor is used to initialize each (array) class object. clockType clocks[100];

58 Destructors  Like constructors, destructors are also functions.  The name of a destructor is the character '~' followed by the name of the class.  The name of the destructor for the class clockType is ~clockType();  A class can have only one destructor and it has no parameters.  The destructor is automatically executed when the class object goes out of scope.

59 Data Abstraction, Classes, and Abstract Data Types  The data type clockType has three data members and the following basic operations: 1. Set the time. 2. Return the time. 3. Print the time. 4. Increment the time by one second. 5. Increment the time by one minute. 6. Increment the time by one hour. 7. Compare the two times to see whether they are equal. Abstract Data Type (ADT: A data type that specifies the logical properties without the implementation details.

60 An ADT has three things associated with it.  The name of the ADT, called type name.  The set of values belonging to the ADT, called domain.  The set of operations on the data.

61 dataTypeName clockType domain Each clockType value is a time of day in the form of hours, minutes, and seconds. operations Set the time. Return the time. Print the time. Increment the time by one second. Increment the time by one minute. Increment the time by one hour. Compare the two times to see whether they are equal.

62 Example 13-8  A list is defined as a set of values of the same type.  All values in a list are of the same type; a convenient way to represent and process a list is to use an array.  You can define a list as an ADT as follows: dataTypeName listType domain Every element of the type listType is a set of, say 1000 numbers. operations Check to see if the list is empty. Check to see if the list is full. Search the list for a given item. Delete an item from the list. Insert an item in the list. Sort the list. Destroy the list. Print the list.

63 The following class defines the list ADT. class listType { public: bool isEmptyList(); bool isFullList(); void search(int searchItem, int& found); void insert(int newElement); void remove(int removeElement); void destroy(); void printList(); listType(); //constructor private: int list[1000]; int length; };

64

65 A STRUCT VERSUS A CLASS  By default the members of a struct are public.  By default the members of a class are private.  You can use the member access specifier private in a struct to make a member private.  Both C++ classes and structs have the same capabilities.  Most programmers restrict their use of structures to adhere to their C-like structure form, and so do not use them to include member functions.  If all of the data members of a class are public and the class has no member functions, you typically use a struct to group these members.

66 INFORMATION HIDING  Implementation file.  Header file (Specification file).  The header file has an extension h.  The implementation file has an extension cpp.  The implementation file must include the header file via the include statement.  In a include statement, user defined header files are enclosed in double quotes while system provided header files are enclosed between angular brackets.

67 //clock.h, the specification file for the class clockType class clockType { public: void setTime(int hours, int minutes, int seconds); //Function to set the time //Post: time is set according to the //parameters: hr = hours; min = minutes; // sec = seconds void getTime(int& hours, int& minutes, int& seconds) //Function to return the time //Post: hours = hr; minutes = min; // seconds = sec void printTime() const; //Function to print the time //Time is printed in the form hh:mm:ss void incrementSeconds(); //Function to increment the time by one second //Post: The time is incremented by one second //If the before-increment time is 23:59:59, the time //is reset to 00:00:00

68 void incrementMinutes(); //Function to increment the time by one minute //Post: The time is incremented by one minute //If the before-increment time is 23:59:53, the time //is reset to 00:00:53 void incrementHours(); //Function to increment the time by one hour //Post: The time is incremented by one hour //If the before-increment time is 23:45:53, the time //is reset to 00:45:53 bool equalTime(const clockType& otherClock) const; //Function to compare the two times //Function returns true if this time is equal to //otherTime, otherwise returns false clockType(int hours, int minutes, int seconds); //Constructor with parameters //Post: The time is set according to //the parameters // hr = hours; min = minutes; sec = seconds clockType(); //Default constructor with parameters //Post: time is set to 00:00:00 // hr = 0; min = 0; sec = 0

69 private: int hr; //store hours int min; //store minutes int sec; //store seconds }; //clockImp.cpp, the implementation file #include #include "clock.h" using namespace std;. //The definition of the member functions of the clockType //goes here..

70 //TestClock.cpp. The user program that uses the class //clockType #include #include "clock.h" using namespace std;. //Place the definitions of the function main and the other //user-defined functions here.

71 EXECUTABLE CODE  To use the class clockType, the program must include the header file clock.h via the include statement. //Program test.cpp #include "clock.h". int main() {. }  The program test.cpp must include only the header file, not the implementation file.

72 To create the executable code to run the program test.cpp, the following steps are required: 1. Separately compile the file clockImp.cpp and create the object code file clockImp.obj. Suppose the command cc invokes the C++ compiler or linker, or both, on the computer’s system command line. The command cc –c clockImp.cpp creates the object code file clockImp.obj. 2. To create the executable code for the source code file test.cpp, compile the source code file test.cpp, create the object code file test.obj, and then link the files test.obj and clockImp.obj to create the executable file test.exe. The following command on the system command line creates the executable file test.exe : cc test.cpp clockImp.obj

73  SDK’s Visual C++, C++ Builder, and CodeWarrior put the editor, compiler, and linker all into one package.  With one command, the program is compiled and linked with the other necessary files.  These systems also manage multiple file programs in the form of a project.  A project consists of several files, called the project files.  These systems usually have a command, called build, rebuild, or make.  When the build, rebuild, or make command is applied to a project, the system automatically compiles and links all files required to create the executable code.  When one or more files in the project change, you can use these commands to recompile and relink the files.

74 Example 13-9 class personType { public: void print() const; //Function to output the first name and last //name in the form firstName lastName void setName(string first, string last); //Function to set firstName and lastName //according to the parameters //Post: firstName = first; lastName = last; void getName(string& first, string& last); //Function to return firstName and lastName via the //parameters //Post: first = firstName; last = lastName; personType(string first, string last); //Constructor with parameters //Set firstName and lastName according to the parameters //Post: firstName = first; lastName = last;

75 personType(); //Default constructor; //Initialize firstName and lastName to empty string //Post: firstName = ""; lastName = ""; private: string firstName; //store the first name string lastName; //store the last name }; void personType::print() const { cout<<firstName<<" "<<lastName; } void personType::setName(string first, string last) { firstName = first; lastName = last; }

76 personType(); //Default constructor; //Initialize firstName and lastName to empty string //Post: firstName = ""; lastName = ""; private: string firstName; //store the first name string lastName; //store the last name };

77

78 void personType::print() const { cout<<firstName<<" "<<lastName; } void personType::setName(string first, string last) { firstName = first; lastName = last; } void personType::getName(string& first, string& last) { first = firstName; last = lastName; }

79 //constructor with parameters personType::personType(string first, string last) { firstName = first; lastName = last; } personType::personType() //default constructor { firstName = ""; lastName = ""; }  You can replace both constructors of the class personType by using a single constructor with default parameters.

80 PROGRAMMING EXAMPLE: CANDY MACHINE A common place to buy candy is the candy machine. A new candy machine is bought for the gym, but it is not working properly. This candy machine currently sells candies, chips, gum, and cookies. You have been asked to write a program for this candy machine so it can be put into operation. The program should : 1. Show the customer the different products sold by the candy machine. 2. Let the customer make the selection. 3. Show the customer the cost of the item selected. 4. Accept money from the customer. 5. Release the item. Input: Item selection and cost of the item. Output: Selected Item.

81 Problem Analysis and Algorithm Design A candy machine has two main components. A built in cash register and several dispensers to hold and release the product. Cash Register class cashRegister { public: int currentBalance(); //Function to show the current amount in the cash //register //Post: The value of the data member cashOnHand is returned void acceptAmount(int amountIn); //This function receives the amount deposited by //the customer and updates the amount in the register. //Post: cashOnHand = cashOnHand + amountIn

82 cashRegister(int cashIn = 500); //Constructor to set the cash in the register to a //specific amount //Post: cashOnHand = cashIn; //If no value is specified when the //object is declared, the default value assigned //to cashOnHand is 500 private: int cashOnHand; //variable to store the cash //in the register };

83

84 int cashRegister::currentBalance() { return cashOnHand; } void cashRegister::acceptAmount(int amountIn) { cashOnHand += amountIn; } cashRegister::cashRegister(int cashIn) { if(cashIn >= 0) cashOnHand = cashIn; else cashOnHand = 500; }

85 Dispenser class dispenserType { public: int count(); //Function to show the number of items in the machine //Post: The value of the data member numberOfProducts // is returned int productCost(); //Function to show the cost of the item //The value of the data member cost is returned void makeSale(); //Function to reduce the number of items by 1 //Post: numberOfProducts = numberOfProducts – 1;

86 dispenserType(int setNoOfProdusts = 50, int setCost = 50); //Constructor to set the cost and number of items //in the dispenser specified by the user //Post: numberOfProducts = setNoOfProducts; // cost = setCost; //If no value is specified for either of the two //parameters, the default values are assigned to the //data members numberOfProducts and cost. private: int numberOfProducts; //variable to store the number //of items in the dispenser int cost; //variable to store the cost of an item };

87

88 dispenserType chips(100,65);

89 int dispenserType::count() { return numberOfProducts; } int dispenserType::productCost() { return cost; } void dispenserType::makeSale() { numberOfProducts--; }

90 //constructor dispenserType::dispenserType(int setNoOfProducts, int setCost) { if(setNoOfProducts >= 0) numberOfProducts = setNoOfProducts; else numberOfProducts = 50; if(setCost >= 0) cost = setCost; else cost = 50; }

91 Main Program When the program executes, it must 1. Show the different products sold by the candy machine. 2. Show how to select a particular product. 3. Show how to terminate the program.  These instructions must be displayed after processing each selection, except exciting the program.  Once the user has made the appropriate selection, the candy machine must act accordingly.  If the user has selected to a buy a product and if the product is available, the candy machine should show the cost of the product and ask the user to deposit the money.  If the money deposited is at least the cost of the item, the candy machine should sell the item and display an appropriate message.

92 1. Show the selection to the customer. 2. Get selection. 3. If selection is valid and the dispenser corresponding to the selection is not empty, sell the product. showSelection : a. *** Welcome to Shelly's Candy Shop ***" b. To select an item, enter c. 1 for Candy d. 2 for Chips e. 3 for Gum f. 4 for Cookies g. 9 to exit

93 void showSelection() { cout<<"*** Welcome to Shelly's Candy Shop ***"<<endl; cout<<"To select an item, enter "<<endl; cout<<"1 for Candy"<<endl; cout<<"2 for Chips"<<endl; cout<<"3 for Gum"<<endl; cout<<"4 for Cookies"<<endl; cout<<"9 to exit"<<endl; }//end showSelection

94 sellProduct a. If the dispenser is nonempty i. Show and prompt the customer to enter the cost of the item. ii. Get the amount entered by the customer. iii. If the amount entered by the customer is less than the cost of the product 1. Show and prompt the customer to enter the additional amount. 2. Calculate the total amount entered by the customer. iv. If the amount entered by the customer is at least the cost of the product 1. Update the amount in the cash register. 2. Sell the product, that is, decrement the number of items in the dispenser by 1. 3. Display an appropriate message. v. If the amount entered by the user is less than the cost of the item, return the amount. b. If the dispenser is empty, tell the user that this product is sold out.

95 void sellProduct(dispenserType& product, cashRegister& pCounter) { int amount; //variable to hold the amount entered int amount2; //variable to hold the extra amount needed if(product.count() > 0) //Step a { cout<<"Please deposit "<<product.productCost() <<" cents"<<endl;//Step a.i cin>>amount;//Step a.ii if(amount < product.productCost())//Step a.iii { cout<<"Please deposit another " <<product.productCost() – amount <<" cents"<<endl; //Step a.iii.1 cin>>amount2;//Step a.iii.2 amount = amount + amount2;//Step a.iii.3 }

96 if(amount >= product.productCost())//Step a.iv { pCounter.acceptAmount(amount);//Step a.iv.1 product.makeSale();//Step a.iv.2 cout<<"Collect your item at the bottom" <<" and enjoy."<<endl; //Step a.iv.3 } else cout<<"The amount is not enough. " <<"Collect what you deposited."<<endl; //Step a.v cout<<"*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" <<endl<<endl; } else cout<<"Sorry this item is sold out."<<endl; //Step b }//end sellProduct

97 The algorithm for the function main is 1. Create the cash register, that is, declare a variable of the type cashRegister. 2. Create four dispensers. That is, declare four objects of the type dispenserType and also initialize these objects. For example, the statement dispenserType candy(100, 50); creates a dispenser object, candy, to hold candies. The number of items in the dispenser is 100 and the cost of an item is 50 cents. 3. Declare additional variables as necessary. 4. Show selection, call the function showSelection. 5. Get the selection. 6. While not done (a selection of 9 exists the program). a. Sell product, call the function sellProduct. b. Show selection, call the function showSelection. c. Get selection.

98 int main() { cashRegister counter;//Step 1 dispenserType candy(100,50); //Step 2 dispenserType chips(100,65);//Step 2 dispenserType gum(75,45);//Step 2 dispenserType cookies(100,85);//Step 2 int choice; //Step 3 showSelection();//Step 4 cin>>choice;//Step 5 while(choice != 9)//Step 6 { switch(choice)//Step 6a { case 1: sellProduct(candy, counter); break; case 2: sellProduct(chips, counter); break; case 3: sellProduct(gum, counter); break; case 4: sellProduct(cookies, counter); break; default: cout<<"Bad Selection"<<endl; }//end switch

99 showSelection();//Step 6b cin>>choice;//Step 6c }//end while return 0; }//end main

100 Complete Program Listing //Candy Machine Header File class cashRegister { public: int currentBalance(); //Function to show the current amount in the cash //register //Post: The value of the data member cashOnHand is returned void acceptAmount(int amountIn); //This function receives the amount deposited by //the customer and updates the amount in the register. //Post: cashOnHand = cashOnHand + amountIn cashRegister(int cashIn = 500); //Constructor to set the cash in the register to a //specific amount //Post: cashOnHand = cashIn; //If no value is specified when the //object is declared, the default value assigned //to cashOnHand is 500

101 private: int cashOnHand; //variable to store the cash //in the register }; class dispenserType { public: int count(); //Function to show the number of items in the machine //Post: The value of the data member numberOfProducts // is returned int productCost(); //Function to show the cost of the item //The value of the data member cost is returned void makeSale(); //Function to reduce the number of items by 1 //Post: numberOfProducts = numberOfProducts – 1;

102 dispenserType(int setNoOfProdusts = 50, int setCost = 50); //Constructor to set the cost and number of items //in the dispenser specified by the user //Post: numberOfProducts = setNoOfProducts; // cost = setCost; //If no value is specified for either of the two //parameters, the default values are assigned to the //data members numberOfProducts and cost. private: int numberOfProducts; //variable to store the number //of items in the dispenser int cost; //variable to store the cost of an item };

103 //Implementation file candyMachineImp.cpp #include #include "candyMachine.h" using namespace std; int cashRegister::currentBalance() { return cashOnHand; } void cashRegister::acceptAmount(int amountIn) { cashOnHand += amountIn; } cashRegister::cashRegister(int cashIn) { if(cashIn >= 0) cashOnHand = cashIn; else cashOnHand = 500; }

104 int dispenserType::count() { return numberOfProducts; } int dispenserType::productCost() { return cost; } void dispenserType::makeSale() { numberOfProducts--; } dispenserType::dispenserType(int setNoOfProducts, int setCost) { if(setNoOfProducts >= 0) numberOfProducts = setNoOfProducts; else numberOfProducts = 50; if(setCost >= 0) cost = setCost; else cost = 50; }

105 //Main program: #include #include "candyMachine.h" using namespace std; void showSelection(); void sellProduct(dispenserType& product, cashRegister& pCounter); int main() { cashRegister counter;//Step 1 dispenserType candy(100,50); //Step 2 dispenserType chips(100,65);//Step 2 dispenserType gum(75,45);//Step 2 dispenserType cookies(100,85);//Step 2 int choice; //Step 3 showSelection();//Step 4 cin>>choice;//Step 5 while(choice != 9)//Step 6 {

106 switch(choice)//Step 6a { case 1: sellProduct(candy, counter); break; case 2: sellProduct(chips, counter); break; case 3: sellProduct(gum, counter); break; case 4: sellProduct(cookies, counter); break; default: cout<<"Bad Selection"<<endl; }//end switch showSelection();//Step 6b cin>>choice;//Step 6c }//end while return 0; }//end main //Place the definitions of the functions showSelection and //sellProduct

107 Sample Run: The user input is in red. *** Welcome to Shelly's Candy Shop *** To select an item, enter 1 for Candy 2 for Chips 3 for Gum 4 for Cookies 9 to exit 1 Please deposit 50 cents 50 Collect item at the bottom and enjoy *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

108 *** Welcome to Shelly's Candy Shop *** To select an item, enter 1 for Candy 2 for Chips 3 for Gum 4 for Cookies 9 to exit 3 Please deposit 45 cents 45 Collect item at the bottom and enjoy *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

109 *** Welcome to Shelly's Candy Shop *** To select an item, enter 1 for Candy 2 for Chips 3 for Gum 4 for Cookies 9 to exit 9


Download ppt "CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class."

Similar presentations


Ads by Google