Chapter 10 Class Design
Chapter 10 Class Design
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Objectives
To process strings using the string class (10.2). To develop functions with object arguments (10.3-4). To store and process objects in arrays (10.5-6). To distinguish between instance and static variables and functions (10.7). To define constant functions to prevent data fields from being modified accidentally (10.8). To explore the differences between the procedural paradigm and object-oriented paradigm (10.9). To design a class for body mass index (10.9). To develop classes for modeling composition relationships (10.10). To design a class for a stack (10.11). To describe the software life cycle (10.12). To design classes that follow the class-design guidelines (10.13).
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Constructing a String
You can create an empty string using strings no-arg constructor like this one: string newString;
You can create a string object from a string value or from an array of characters. To create a string from a string literal, use a syntax like this one:
string newString(stringLiteral);
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Appending a String
You can use several overloaded functions to add new contents to a string. For example, see the following code:
string s1("Welcome"); s1.append(" to C++"); // appends " to C++" to s1 cout << s1 << endl; // s1 now becomes Welcome to C++ string s2("Welcome"); s2.append(" to C and C++", 0, 5); // appends " to C" to s2 cout << s2 << endl; // s2 now becomes Welcome to C string s3("Welcome"); s3.append(" to C and C++", 5); // appends " to C" to s3 cout << s3 << endl; // s3 now becomes Welcome to C string s4("Welcome"); s4.append(4, 'G'); // appends "GGGG" to s4 cout << s4 << endl; // s4 now becomes WelcomeGGGG
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Assigning a String
You can use several overloaded functions to assign new contents to a string. For example, see the following code:
string s1("Welcome"); s1.assign("Dallas"); // assigns "Dallas" to s1 cout << s1 << endl; // s1 now becomes Dallas string s2("Welcome"); s2.assign("Dallas, Texas", 0, 5); // assigns "Dalla" to s2 cout << s2 << endl; // s2 now becomes Dalla string s3("Welcome"); s3.assign("Dallas, Texas", 5); // assigns "Dalla" to s3 cout << s3 << endl; // s3 now becomes Dalla string s4("Welcome"); s4.assign(4, 'G'); // assigns "GGGG" to s4 cout << s4 << endl; // s4 now becomes GGGG
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Comparing Strings
Often, in a program, you need to compare the contents of two strings. You can use the compare function. This function works in the same way as the C-string strcmp function and returns a value greater than 0, 0, or less than 0. For example, see the following code: string s1("Welcome"); string s2("Welcomg"); cout << s1.compare(s2) << endl; // returns -2 cout << s2.compare(s1) << endl; // returns 2 cout << s1.compare("Welcome") << endl; // returns 0
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Obtaining Substrings
You can obtain a single character from a string using the at function. You can also obtain a substring from a string using the substr function. For example, see the following code: string s1("Welcome"); cout << s1.substr(0, 1) << endl; // returns W cout << s1.substr(3) << endl; // returns come cout << s1.substr(3, 3) << endl; // returns com
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Searching in a String
You can use the find function to search for a substring or a character in a string. For example, see the following code:
string s1("Welcome to HTML"); cout << s1.find("co") << endl; // returns 3 cout << s1.find("co", 6) << endl; // returns -1 cout << s1.find('o') << endl; // returns 4 cout << s1.find('o', 6) << endl; // returns 9
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
10
11
String Operators
Operator [] = + += << >> ==, !=, <, <=, >, >= Description Accesses characters using the array subscript operators. Copies the contents of one string to the other. Concatenates two strings into a new string. Appends the contents of one string to the other. Inserts a string to a stream Extracts characters from a stream to a string delimited by a whitespace or the null terminator character. Six relational operators for comparing strings.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
12
Reading Strings
string city; cout << "Enter a city: "; cin >> city; // Read to array city cout << "You entered " << city << endl;
string city; cout << "Enter a city: "; getline(cin, city, '\n'); // Same as getline(cin, city) cout << "You entered " << city << endl;
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
13
myCircle: Circle
radius: 5.0
PassObjectByValue
Run Run
14
PassObjectByReference
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Checking Palindromes
A string is a palindrome if it reads the same forward and backward. The words mom, dad, and noon, for example, are all palindromes. How do you write a program to check whether a string is a palindrome?
CheckPalindrome
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Run
15
Array of Objects
Circle circleArray[3] = {Circle(3), Circle(4), Circle(5)};
TotalArea
Run
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
16
DeckOfCards
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Run
17
Circle
-radius: double -numberOfObjects: int
numberOfObjects
radius
UML Notation: +: public variables or functions -: private variables or functions underline: static variables or functions
Circle5.h Circle5.cpp
TestCircle5.cpp
Run
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
18
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
19
Instance or Static?
How do you decide whether a variable or function should be instance or static? A variable or function that is dependent on a specific instance of the class should be an instance variable or function. A variable or function that is not dependent on a specific instance of the class should be a static variable or function. For example, every circle has its own radius. Radius is dependent on a specific circle. Therefore, radius is an instance variable of the Circle class. Since the getArea function is dependent on a specific circle, it is an instance function. Since numberOfObjects is not dependent on any specific instance, it should be declared static.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
20
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Object-Oriented Thinking
The book introduced fundamental programming techniques for problem solving using loops, functions, and arrays. The study of these techniques lays a solid foundation for object-oriented programming. Classes provide more flexibility and modularity for building reusable software. This section improves the solution for a problem introduced in Chapter 3 using the objectoriented approach. From the improvements, you will gain insight on the differences between the procedural programming and object-oriented programming and see the benefits of developing reusable code using objects and classes.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
22
BMI.h
BMI.cpp
UseBMIClass
Run
23
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
+addStudent(student: String): void Adds a new student to the course list. +getStudents(): String[] Returns the students for the course. +getNumberOfStudents(): int Returns the number of students for the course.
Course
TestCource
Run
24
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
An array to store integers in the stack. The number of integers in the stack. Constructs an empty stack with a default capacity of 16. Constructs an empty stack with a specified capacity. Returns true if the stack is empty. Returns the integer at the top of the stack without removing it from the stack. Stores an integer into the top of the stack. Removes the integer at the top of the stack and returns it. Returns the number of elements in the stack.
TestStackOfIntegers
Run
25
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Data1
Data2 Data1
Data2
Data1
Data1
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
26
. . .
elements[size-1] top capacity
. . .
elements[1] elements[0] bottom
size
StackOfIntegers
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
27
Object-Oriented Thinking
Procedural vs. Object-Oriented
The get methods for these data fields are provided in the class, but omitted in the UML diagram for brevity. The name of the person. The age of the person. The weight of the person in pounds. The height of the person in inches. Creates a BMI object with the specified name, age, weight, and height. Creates a BMI object with the specified name, weight, height, and a default age 20. Returns the BMI. Returns the BMI status (e.g., normal, overweight, etc.)
BMI .h
BMI .cpp
BMI -name: String -age: int -weight: double -height: double +BMI(name: String, age: int, weight: double, height: double) +BMI(name: String, weight: double, height: double) +getBMI(): double +getStatus(): String
TestPerson
Run
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
28
Object Composition
Composition is actually a special case of the aggregation relationship. Aggregation models has-a relationships and represents an ownership relationship between two objects. The owner object is called an aggregating object and its class an aggregating class. The subject object is called an aggregated object and its class an aggregated class.
Composition
1 1
Aggregation
Name
Student
1..3
Address
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
29
Class Representation
An aggregation relationship is usually represented as a data field in the aggregating class. For example, the relationship in Figure 10.6 can be represented as follows:
class Name { ... } class Student { private: Name name; Address address; ... } Aggregated class Aggregating class Aggregated class class Address { ... }
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
30
Aggregation or Composition
Since aggregation and composition relationships are represented using classes in similar ways, many texts dont differentiate them and call both compositions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
31
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
32
Data2 Data1
Data2 Data1
Data1
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
33
Class UML
The StackOfIntegers class encapsulates the stack storage and provides the operations for manipulating the stack.
StackOfIntegers -elements: int[100] -size: int +StackOfIntegers() +empty(): bool +peek(): int +push(value: int): int +pop(): int
+getSize(): int
An array to store integers in the stack. The number of integers in the stack. Constructs an empty stack. Returns true if the stack is empty. Returns the integer at the top of the stack without removing it from the stack. Stores an integer into the top of the stack. Removes the integer at the top of the stack and returns it. Returns the number of elements in the stack.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
34
Implementation
elements[capacity 1]
. . .
elements[size-1] top capacity
. . .
elements[1] elements[0] bottom
size
StackOfIntegers.h TestStackOfIntegers
StackOfIntegers.cpp Run
35
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
Implementation
Testing
Deployment
Maintenance
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
36
Requirement Specification
Requirement Specification System Analysis System Design
A formal process that seeks to understand the problem and document in detail what the software system needs to do. This phase involves close interaction between users and designers.
Implementation
Testing
Most of the examples in this book are simple, and their requirements are clearly stated. In the real world, however, problems are not well defined. You need to study a problem carefully to identify its requirements.
Deployment
Maintenance
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
37
System Analysis
Requirement Specification System Analysis System Design
Seeks to analyze the business process in terms of data flow, and to identify the systems input and output.
Implementation
Part of the analysis entails modeling the systems behavior. The model is intended to capture the essential elements of the system and to define services to the system.
Testing
Deployment
Maintenance
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
38
System Design
Requirement Specification System Analysis System Design
Implementation
Testing
This phase involves the use of many levels of abstraction to decompose the problem into manageable components, identify classes and interfaces, and establish relationships among the classes and interfaces.
Deployment
Maintenance
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
39
Implementation
Requirement Specification System Analysis System Design
The process of translating the system design into programs. Separate programs are written for each component and put to work together.
Implementation
This phase requires the use of a programming language like Java. The implementation involves coding, testing, and debugging.
Testing
Deployment
Maintenance
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
40
Testing
Requirement Specification System Analysis System Design
Ensures that the code meets the requirements specification and weeds out bugs.
Implementation
An independent team of software engineers not involved in the design and implementation of the project usually conducts such testing.
Testing
Deployment
Maintenance
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
41
Deployment
Requirement Specification System Analysis System Design
Implementation
For a Java applet, this means installing it on a Web server; for a Java application, installing it on the client's computer.
Testing
Deployment
Maintenance
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
42
Maintenance
Requirement Specification System Analysis System Design
Implementation
A software product must continue to perform and improve in a changing environment. This requires periodic upgrades of the product to fix newly discovered bugs and incorporate changes.
Testing
Deployment
Maintenance
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
43
class should describe a single entity or a set of similar operations. A single entity with too many responsibilities can be broken into several classes to separate responsibilities.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
44
standard programming style and naming conventions. Choose informative names for classes, data fields, and functions. A popular style in C++ is to place the data declaration after the functions, and place constructors before functions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
45
class should use the private modifier to hide its data from direct access by clients. This makes the class easy to maintain. Provide a get function only if you want the field to be readable, and provide a set function only if you want the field to be updateable. A class should also hide functions not intended for client use. Such functions should be defined as private.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
46
Users can incorporate classes in many different combinations, orders, and environments. Therefore, you should design a class that imposes no restrictions on what or when the user can do with it, design the properties in a way that lets the user set them in any order and with any combination of values, and design functions independently of their order of occurrence. For example, the Loan class contains the functions setLoanAmount, setNumberOfYears, and setAnnualInterestRate. The values of these properties can be set in any order.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
47
are designed for use by many different customers. In order to be useful in a wide range of applications, a class should provide a variety of ways for customization through properties and functions. For example, the string class contains more than 20 functions that are useful for a variety of applications.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
48
A variable or function that is dependent on a specific instance of the class should be an instance variable or function. A variable that is shared by all the instances of a class should be declared static. For example, the variable numberOfObjects in Circle in Listing 10.9, is shared by all the objects of the Circle class, and therefore is declared static. A function that is not dependent on a specific instance should be declared as a static function. For instance, the getNumberOfObjects function in Circle is not tied to any specific instance, and therefore is declared as static functions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200
49