Chapter 11: Classes and Data Abstraction

Slides:



Advertisements
Similar presentations
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 12: Classes and Data Abstraction
True or false A variable of type char can hold the value 301. ( F )
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 11: Classes and Data Abstraction.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Chapter 8 User-Defined Classes and ADTs. Chapter Objectives Learn about classes Learn about private, protected, public, and static members of a class.
1 Lecture 29 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 11: Classes and Data Abstraction
Software Engineering Principles and C++ Classes
Chapter 8: User-Defined Classes and ADTs J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Data Structures Using C++1 Chapter 1 Software Engineering Principles and C++ Classes.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
CLASSES AND DATA ABSTRACTION
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
SEN 909 OO Programming in C++ Final Exam Multiple choice, True/False and some minimal programming will be required.
Chapter 11: Classes and Data Abstraction. C++ Programming: Program Design Including Data Structures, Fourth Edition2 Objectives In this chapter, you will:
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Data Structures Using C++1 Chapter 1 -Software Engineering Principles -ADT and Classes.
Chapter 8: User-Defined Classes and ADTs
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Data Structures Using C++1 Chapter 1 Software Engineering Principles and C++ Classes.
C++ Classes and Data Structures Jeffrey S. Childs
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 8: User-Defined Classes and ADTs J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 12: Classes and Data Abstraction.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 11: Classes and Data Abstraction.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 12: Classes and Data Abstraction.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 11: Classes and Data Abstraction.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Data Structures Using Java1 Chapter 1 Software Engineering Principles and Java Classes.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 11: Classes and Data Abstraction.
1 CS 132 Spring 2008 Chapter 1 Software Engineering Principles and C++ Classes.
CHAPTER 13 CLASSES AND DATA ABSTRACTION. In this chapter, you will:  Learn about classes  Learn about private, protected, and public members of a class.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Chapter 12 Classes and Abstraction
EGR 2261 Unit 13 Classes Read Malik, Chapter 10.
Chapter 7: User-Defined Functions II
Java Programming: Guided Learning with Early Objects
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Chapter Structured Types, Data Abstraction and Classes
User-Defined Classes and ADTs
Introduction to Structured Data Types and Classes
Classes and Data Abstraction
Chapter 8: User-Defined Classes and ADTs
User-Defined Classes and ADTs
Chapter 9 Introduction To Classes
Chapter 12: Classes and Data Abstraction
Classes and Objects Systems Programming.
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

//*********** 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

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

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

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

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

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

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

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

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

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

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

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