Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 11: Classes and Data Abstraction

Similar presentations


Presentation on theme: "Chapter 11: Classes and Data Abstraction"— Presentation transcript:

1 Chapter 11: Classes and Data Abstraction
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 11: Classes and Data Abstraction

2 Objectives 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) C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

3 Objectives Explore how classes are used to implement ADTs
Learn about information hiding Explore how information hiding is implemented in C++ Learn about the static members of a class C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

4 Classes Class: collection of a fixed number of components
The components of a class are called members The general syntax for defining a class: class classIdentifier { classMemberList }; Class member can be a variable or a function C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

5 Classes (continued) If a member of a class is a variable
It is declared like any other variable In the definition of the class Cannot initialize a variable when you declare it If a member of a class is a function Function prototype is listed to declare that member Function members can (directly without passing it as a parameter) access any data or function member of the class C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

6 Classes (continued) Class is a reserved word
Class defines a data type, no memory is allocated Don’t forget the semicolon after the closing brace of the class C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

7 Classes (continued) Three categories of class members
private public protected By default, all members of a class are private It cannot be accessed outside the class C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

8 Classes (continued) A public member is accessible outside the class
To make a member of a class public Use the label public with a colon private, protected, and public are reserved words C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

9 A + sign in front of a member name indicates a public member
A - sign in front of a member name indicates a private member A # sign in front of a member name indicates a protected member C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

10 Variable (Object) Declaration
Once a class is defined, then you can declare variables of that type The syntax for declaring a class object is the same as for declaring any other variable clockType myClock; // memory is allocated clockType yourClock; // memory is allocated In C++ terminology, a class variable is called a class object or class instance C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

11 Object-Oriented Design
A technique for developing a program in which the solution is expressed in terms of objects -- self- contained entities composed of data and operations on that data. cin cout >> << get Private data setf Private data . . ignore setw 11 expanded by J. Goetz, 2004

12 Two Programming Methodologies
Functional Object-Oriented Decomposition Design OBJECT Operations Data FUNCTION FUNCTION OBJECT Operations Data OBJECT Operations Data FUNCTION expanded by J. Goetz, 2004

13 What is an object? OBJECT Operations Data set of functions
internal state Operations Data expanded by J. Goetz, 2004

14 An object contains data and operations
checkingAccount OpenAccount Private data: accoutNumber balance WriteCheck MakeDeposit IsOverdrawn GetBalance expanded by J. Goetz, 2004

15 Accessing Class Members
Once an object is declared It can access (from outside the class) the public members of the class Syntax to access class members: classVariableName.memberName The dot (. ) is called the member access operator myClock.setTime (4, 3, 25); C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

16 Built-in Operations on Classes
Arithmetic operators cannot be used on class objects unless the operators are overloaded You cannot use relational operators to compare two class objects for equality The four built-in operations that are valid for class objects are: 1. member access (.) and 2. assignment (=) clockType myClock, yourClock; myClock = yourClock; 3. pass parameters to a function by value or by reference 4. return as value of a function C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

17 Class Scope An object can be
automatic – destroyed when the control exists the surrounding block or static – created once when the control reaches its declaration, and destroyed when the program terminates A member of the class is local to the class A class object has the same scope as other variables declared in the same block. You access a class member outside the class by using the class object name and the member access operator (.) myClock.setTime (4, 3, 25); C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

18 Functions and Classes Objects can be passed as parameters to functions
by value or by reference and returned as function values If an object is passed by value Contents of data members of the actual parameter are copied into the corresponding data members of the formal parameter C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

19 Reference Parameters & Variables
Passing by value might require a large amount of storage space and 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

20 Reference Parameters & Variables
Pass by reference is an efficient way to pass a variable as a parameter If a variable is passed by reference Then the actual parameter changes when the formal parameter changes You can pass a variable by reference and still prevent the function from changing its value Use the keyword const in the formal parameter declaration void testTime( const clockType& otherClock) { clockType dClock; …. otherClock.setTime(5, 6, 39); // illegal b/c it cannot be changed otherClock = dClock; // illegal b/c it cannot be changed } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

21 Accessor and Mutator Functions
Accessor (observer) function: member function that only accesses (does not modify) the value(s) of the data member(s) getTime(); Mutator (transformer) function: member function that modifies the value(s) of the data member(s) void setTime(); As a safeguard can include const; Constant function: Member function that cannot modify data members Include reserved word const at the end of the function heading void getTime() const; void printTime() const; void equalTime() const; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

22 Data Abstraction, Classes, and Abstract Data Types - ADT
Separating design details from usage Separating the logical properties from the implementation details Abstraction can also be applied to data C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

23 Abstraction is the separation of the essential qualities of an object from the details of how it works or is composed focuses on the what, not the how The principle of deferring details to as a level as possible should be applied to designing data structures and designing algorithms. This allows to separate the logical description (properties) from the implementation. is necessary for managing large, complex software projects expanded by J. Goetz, 2004

24 Control Abstraction separates the logical properties of an action from its implementation . Search (list, item, length, where, found); the function call depends on the function’s specification (description), not its implementation (algorithm) expanded by J. Goetz, 2004

25 Information Hiding Class implementation details are hidden from the client’s view. This is called information hiding. Public functions of a class provide the interface between the client code and the class objects. client code abstraction barrier specification implementation expanded by J. Goetz, 2004

26 Data Abstraction LOGICAL PROPERTIES IMPLEMENTATION
separates the logical properties of a data type from its implementation LOGICAL PROPERTIES IMPLEMENTATION What are the possible values? How can this be done in C++? What operations will be needed? How can data types be used? expanded by J. Goetz, 2004

27 Abstract Data Types ADT
Abstract Data Type (ADT): data type that specifies logical properties without the implementation details An ADT has 3 properties Name of the ADT (type name) Set of values belonging to the ADT (domain) Set of operations on the data C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

28 Information Hiding Information hiding: hiding the details of the operations on the data Interface (header) file: contains the specification details Implementation file: contains the implementation details C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

29 Information Hiding (continued)
Include comments in the header file with the function prototypes that briefly describe the functions Specify any preconditions – must be true before function is called and/or postconditions - must be true after the function is completed C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

30 Information Hiding (continued)
Header file has an extension .h Implementation file has an extension .cpp Implementation file must include header file via include statement In an include statement User-defined header files are enclosed in double quotes #include "clockType.h" System-provided header files are enclosed between angular brackets #include <iostream> C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

31 //clockType.h, the specification file for the class clockType
{ public: void setTime(int hours, int minutes, int seconds); //Function to set the time. //The time is set according to the parameters. //Postcondition: hr = hours; min = minutes; // sec = seconds // The function checks whether the values of // hours, minutes, and seconds are valid. If a // value is invalid, the default value 0 is // assigned. void getTime(int& hours, int& minutes, int& seconds) const; //Function to return the time. //Postcondition: hours = hr; minutes = min; // seconds = sec void printTime() const; //Function to print the time. //Postcondition: The time is printed in the form // hh:mm:ss. void incrementSeconds(); //Function to increment the time by one second. //Postcondition: The time is incremented by one // second. // If the before-increment time is 23:59:59, the // time is reset to 00:00:00. void incrementMinutes(); //Function to increment the time by one minute. // 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. //Postcondition: 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. //Postcondition: Returns true if this time is // equal to otherClock; otherwise, // returns false. clockType(int hours, int minutes, int seconds); //constructor with parameters //The time is set according to the parameters. //Postcondition: hr = hours; min = minutes; // sec = seconds // The constructor checks whether the values of // hours, minutes, and seconds are valid. If a // value is invalid, the default value 0 is // assigned. clockType(); //default constructor with parameters //The time is set to 00:00:00. //Postcondition: hr = 0; min = 0; sec = 0 private: int hr; //variable to store the hours int min; //variable to store the minutes int sec; //variable to store the seconds }; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

32 //Implementation File for the class clockType
#include <iostream> #include "clockType.h" using namespace std; 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; min = 0; if (0 <= seconds && seconds < 60) sec = seconds; sec = 0; } void clockType::getTime(int& hours, int& minutes, int& seconds) const hours = hr; minutes = min; seconds = sec; void clockType::incrementHours() hr++; if(hr > 23) void clockType::incrementMinutes() { min++; if (min > 59) min = 0; incrementHours(); } 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 << min << ":"; if (sec < 10) cout << sec; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

33 bool clockType::equalTime(const clockType& otherClock) const {
return (hr == otherClock.hr && min == otherClock.min && sec == otherClock.sec); } clockType::clockType(int hours, int minutes, int seconds) //constructor if (0 <= hours && hours < 24) hr = hours; else hr = 0; if (0 <= minutes && minutes < 60) min = minutes; min = 0; if (0 <= seconds && seconds < 60) sec = seconds; sec = 0; clockType::clockType() //default constructor example: myClock.setTime (4, 3, 25); yourClock.setTime (4, 28, 30); consider: if (myClock.equalTime(yourClock) ) {….} //see p.553 fig. 11-8 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

34 //The user (driver) program //see p.560 for sample run
//that uses the class clockType #include <iostream> #include "clockType.h" using namespace std; int main() { clockType myClock; //default constructor called clockType yourClock; //default constructor called int hours; int minutes; int seconds; //set the time of myClock myClock.setTime(5, 4, 30); //Line 1 cout << "Line 2: myClock: "; //Line 2 myClock.printTime(); //print the time of myClock //Line 3 cout << endl; //Line 4 cout << "Line 5: yourClock: "; //Line 5 yourClock.printTime(); //print the time of yourClock Line 6 cout << endl; //Line 7 //set the time of yourClock yourClock.setTime(5, 45, 16); //Line 8 cout << "Line 9: After setting, yourClock: "; //Line 9 yourClock.printTime(); //print the time of yourClock Line 10 cout << endl; //Line 11 //compare myClock and yourClock 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 the hours, minutes, and " << "seconds: "; //Line 16 cin >> hours >> minutes >> seconds; //Line 17 cout << endl; //Line 18 //set the time of myClock using the value of the //variables hours, minutes, and seconds myClock.setTime(hours, minutes, seconds); //Line 19 cout << "Line 20: New myClock: "; //Line 20 myClock.printTime(); //print the time of myClock //Line 21 cout << endl; //Line 22 //increment the time of myClock by one second myClock.incrementSeconds(); //Line 23 cout << "Line 24: After incrementing myClock by " << "one second, myClock: "; //Line 24 myClock.printTime(); //print the time of myClock //Line 25 cout << endl; //Line 26 //retrieve the hours, minutes, and seconds of the //object myClock myClock.getTime(hours, minutes, seconds); //Line 27 //output the value of hours, minutes, and seconds cout << "Line 28: hours = " << hours << ", minutes = " << minutes << ", seconds = " << seconds << endl; //Line 28 return 0; }//end main C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

35 Scope Resolution Operator ( :: )
C++ programs typically use several class types different classes can have member functions with the same identifier, like printTime( ) member selection operator is used to determine the class whose member function printTime( ) is invoked currentTime .printTime( ) ; // class clockType numberZ . printTime( ) ; // class ComplexNumberType in the implementation file, the scope resolution operator is used in the heading before the function member’s name to specify its class void clockType :: printTime( ) const { } expanded by J. Goetz, 2004

36 Order of public and private Members of a Class
C++ has no fixed order in which you declare public and private members By default all members of a class are private Use the member access specifier public to make a member available for public access C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

37 Constructors Use constructors to guarantee that data members of a class are initialized Two types of constructors: With parameters Without parameters is called the default constructor C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

38 Constructors (continued)
Constructor name same as class name All constructors of a class have the same name has no return type nor a void If a class has > 1 constructor They must have different sets of parameters Which constructor executes depends on the types of values passed to the object when it is called (declared) C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

39 Invoking a Constructor
A constructor is automatically executed when a class variable is declared To invoke the default constructor: className classObjectName; e.g. clockType myClock; //default constructor called To invoke parameterized constructor: className classObjectName(argument1, argument2, ...); where argument1, argument2, etc. is a variable or an expression clockType myClock (4, 3, 25); C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

40 Invoking a Constructor with Parameters
The number of arguments and their type should match the formal parameters (in the order given) of one of the constructors If the type of the arguments does not match the formal parameters of any constructor (in the order given) C++ uses type conversion for the best match C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

41 Classes and Constructors: A Precaution
If a class has no constructor(s) C++ automatically provides the default constructor However, object declared is still uninitialized If a class includes constructor(s) with parameter(s) and does not include default constructor C++ does not provide default constructor to avoid pitfalls if a class has constructor(s) provide default constructor. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

42 Automatic invocation of constructors occurs
clockType departureTime ; // default constructor invoked clockType movieTime = clockType (19, 30, 0 ) ; // parameterized constructor clockType movieTime (19, 30, 0 ) ; // parameterized constructor - more efficient // b/c no copy is involved departureTime movieTime setTime setTime getTime getTime printTime Private data: hrs mins secs printTime Private data: hrs mins secs incrementSeconds incrementSeconds 19 30 incrementSeconds incrementSeconds incrementSeconds incrementSeconds equalTime equalTime expanded by J. Goetz, 2004

43 Arrays of Class Objects (Variables) and Constructors
If a class has constructors and you declare an array of class objects The class should have the default constructor The default constructor is used to initialize each (array) class object For example: clockType clocks[100]; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

44 Destructors are functions without any type
The name of a destructor is the character '~' followed by class name The name of the destructor clockType: ~clockType(); A class can have only one destructor It has no parameters The destructor is automatically executed when the class object goes out of scope C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

45 A struct Versus a Class By default:
members of a struct are public members of a class are private The member access specifier private can be used in a struct to make a member private Classes and structs have the same capabilities C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

46 A struct Versus a Class (continued)
The definition of a struct was expanded to include member functions, constructors and destructors If all data members of a class are public and there are no member functions Use a struct C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

47 Executable Code To use an object in a program
The program must be able to access the implementation Visual C++, C++ Builder, and CodeWarrior put the editor, compiler, and linker into a 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

48 Separate Compilation and Linking of Files p.582
specification file main program clockType.h implementation file client.cpp clockType.cpp #include “clockType.h” Compiler Compiler client.obj clockType.obj Linker client.exe expanded by J. Goetz, 2004

49 Executable Code (continued)
A project consists of several files, called the project files These systems usually have a command, called build, rebuild, or make when it is applied system automatically compiles and links all files required to create the executable code When >= 1 files in the project change You can use these commands to recompile and relink the files C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

50 Static Members of a Class p.585
Use the keyword static to declare a function or variable of a class as static A public static member, function or data, of a class can be accessed using the class name and the scope resolution operator C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

51 static int count; //public static data member
#include <iostream> #include "illustrate.h" using namespace std; int illustrate::count = 0; int illustrate::y = 0; void illustrate::print() const { cout << "x = " << x << ", y = " << y << ", count = " << count << endl; } void illustrate::setX(int a) x = a; void illustrate::incrementY() y++; illustrate::illustrate(int a) class illustrate { public: static int count; //public static data member void print() const; //Function to output x, y, and count. void setX(int a); //Function to set x. //Postcondition: x = a; static void incrementY(); //static function //Function to increment y by 1. //Postcondition: y = y + 1 illustrate(int a = 0); //constructor //If no value is specified for a, x = 0; private: int x; static int y //private static data member }; #include <iostream> #include "illustrate.h" using namespace std; int main() { illustrate illusObject1(3); //Line 1 illustrate illusObject2(5); //Line 2 illustrate::incrementY(); //Line 3 illustrate::count++; //Line 4 illusObject1.print(); //Line 5 illusObject2.print(); //Line 6 return 0; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

52 Programming Example A common place to buy candy is the candy machine
This candy machine currently sells candies, chips, gum, and cookies A new candy machine is bought for the gym, but it is not working properly You have been asked to write a program so it can be put into operation C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

53 Programming Example (continued)
The program should: Show the customer the different products sold Let the customer make the selection Show the customer the cost of the item Accept money from the customer Release the item Input: item selection and cost of the item Output: selected item C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

54 Problem Analysis A candy machine has two main components
A built in cash register Several dispensers to hold and release the product C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

55 Main Program When the program executes, it must
Show the different products sold Show how to select a particular product Show how to terminate the program This menu must be displayed after processing each selection Once the user has made a selection Candy machine must act accordingly C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

56 Main Program (continued)
If the user wants to a buy a product and the product is available Candy machine should show product cost and ask the user to deposit money If the money deposited is at least the cost of the item Candy machine should sell the item and display an appropriate message C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

57 Menu Show the selection to the customer Get selection
If selection is valid and the dispenser corresponding to the selection is not empty, sell the product C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

58 Menu (continued) The menu (showSelection) looks like:
*** 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

59 sellProduct If the dispenser is nonempty: If the dispenser is empty
Prompt customer to enter the item cost Get the amount entered by the customer If the amount entered by the customer is less than the cost of the product Prompt customer to enter additional amount Calculate total amount entered by the customer If amount entered by the customer is at least the cost of the product Update the amount in the cash register Sell the product, that is, decrement the number of items in the dispenser by 1, display an appropriate message If the amount entered by user is less than the cost of the item, return the amount If the dispenser is empty Tell the user that this product is sold out C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

60 The Function main Create the cashRegister; Create four dispensers;
declare a variable of type cashRegister Create four dispensers; declare and initialize four objects dispenserType 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

61 The Function main (continued)
Declare additional variables as necessary Show menu Get the selection While not done (9 exits) Sell product (sellProduct) Show selection (showSelection) Get selection C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

62 //*********** class dispenserType class dispenserType { public:
int getNoOfItems() const; //Function to show the number of items in the machine. //Postcondition: The value of the data member numberOfItems // is returned. int getCost() const; //Function to show the cost of the item. //The value of the data member cost is returned. //Postcondition: The value of cost is returned. void makeSale(); //Function to reduce the number of items by 1. //Postcondition: numberOfItems-- dispenserType(int setNoOfItems = 50, int setCost = 50); //Constructor to set the cost and number of items in the //dispenser specified by the user. //Postcondition: numberOfItems = setNoOfItems; // cost = setCost; // If no value is specified for a parameter, then its // default values are assigned to the corresponding // data member. private: int numberOfItems; //variable to store the number of //items in the dispenser int cost; //variable to store the cost of an item }; //Candy Machine Header File – candyMachine.h class cashRegister { public: int getCurrentBalance() const; //Function to show the current amount in the cash //register. //Postcondition: The value of cashOnHand is returned. void acceptAmount(int amountIn); //Function to receive the amount deposited by //the customer and update the amount in the register. //Postcondition: cashOnHand = cashOnHand + amountIn; cashRegister(int cashIn = 500); //Constructor to set the cash in the register to a //specific amount. //Postcondition: 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 }; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

63 //Implementation file candyMachineImp.cpp
//This file contains the definitions of the functions //to implement the operations of the classes //cashRegister and dispenserType #include <iostream> #include "candyMachine.h" using namespace std; int cashRegister::getCurrentBalance() const { return cashOnHand; } void cashRegister::acceptAmount(int amountIn) cashOnHand += amountIn; cashRegister::cashRegister(int cashIn) if (cashIn >= 0) cashOnHand = cashIn; else cashOnHand = 500; int dispenserType::getNoOfItems() const { return numberOfItems; } int dispenserType::getCost() const return cost; void dispenserType::makeSale() numberOfItems--; dispenserType::dispenserType(int setNoOfItems, int setCost) if (setNoOfItems >= 0) numberOfItems = setNoOfItems; else numberOfItems = 50; if (setCost >= 0) cost = setCost; cost = 50; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

64 // Main Program - mainProgCandyMachine.cpp #include <iostream>
#include "candyMachine.h" using namespace std; void showSelection(); void sellProduct(dispenserType& product, cashRegister& pCounter); int main() { cashRegister counter; dispenserType candy(100, 50); dispenserType chips(100, 65); dispenserType gum(75, 45); dispenserType cookies(100, 85); int choice; //variable to hold the selection showSelection(); cin >> choice; while (choice != 9) switch (choice) case 1: sellProduct(candy, counter); break; case 2: sellProduct(chips, counter); case 3: sellProduct(gum, counter); case 4: sellProduct(cookies, counter); default: cout << "Invalid selection." << endl; }//end switch }//end while return 0; }//end main 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 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

65 If the dispenser is nonempty:
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.getNoOfItems() > 0) //if dispenser is not empty cout << "Please deposit " << product.getCost() << " cents" << endl; cin >> amount; if (amount < product.getCost()) cout << "Please deposit another " << product.getCost()- amount cin >> amount2; amount = amount + amount2; } if (amount >= product.getCost()) pCounter.acceptAmount(amount); product.makeSale(); cout << "Collect your item at the bottom and enjoy." << endl; else cout << "The amount is not enough. " << "Collect what you deposited." << endl; cout << "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*" << endl << endl; cout << "Sorry, this item is sold out." << endl; }//end sellProduct If the dispenser is nonempty: Prompt customer to enter the item cost Get the amount entered by the customer If the amount entered by the customer is less than the cost of the product Prompt customer to enter additional amount Calculate total amount entered by the customer If amount entered by the customer is at least the cost of the product Update the amount in the cash register Sell the product, that is, decrement the number of items in the dispenser by 1, display an appropriate message If the amount entered by user is less than the cost of the item, return the amount If the dispenser is empty Tell the user that this product is sold out C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

66 Summary Class: collection of a fixed number of components
Members: components of a class Members are accessed by name Members are classified into one of three categories: private, protected, and public Class variables are called class objects or, simply, objects C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

67 Summary The built-in operations on classes are the assignment
member selection using “.” pass parameters to a function by value or by reference return as value of a function Constructors guarantee that the data members are initialized when an object is declared A constructor without parameters is called the default constructor Destructors automatically execute when a class object goes out of scope A class can have only one destructor, and the destructor has no parameters C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

68 Summary Abstract data type (ADT): data type that separates the logical properties from the implementation details A public static member, function or data, of a class can be accessed using the class name and the scope resolution operator illustrate::incrementY(); llustrate::count++; Static data members of a class exist even when no object of the class type exists Instance variables: non-static data members C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

69 Programming Life Cycle
Problem-Solving Phase Analysis and Specification General Solution ( Algorithm ) Verify Implementation Phase Concrete Solution ( Program ) Test Maintenance Phase Use Maintain C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

70 A Tempting Shortcut? DEBUG REVISE REVISE DEBUG DEBUG REVISE Shortcut?
CODE GOAL TEST THINKING CODE C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

71 Testing Often Combines Two Approaches
WHITE BOX BLACK BOX TESTING TESTING Code Coverage Allows us to see the program code while designing the tests. Ensure that each statement in the program is executed at least once. We could say that 75% of the branches of a program have been executed or 50% of the path have been tested (metric based testing). Data Coverage Data values at the boundaries, and possibly middle values, example of each category of inputs can be tested. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

72 How to Test a Program design and implement a test plan
a test plan is a document that specifies the test cases to try, which includes purposes conditions of the test cases inputs, and the expected output implement the test plan by verifying that the program outputs the predicted results C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

73 PHASE RESULT TESTING TECHNIQUE
Problem solving Algorithm Algorithm walk-through Implementation Coded program Code walk-through, Trace Compilation Object program Compiler messages Execution Output Implement test plan C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


Download ppt "Chapter 11: Classes and Data Abstraction"

Similar presentations


Ads by Google