0% found this document useful (0 votes)
49 views

Chapter 10 Class Design

The document discusses class design in C++. It covers topics such as using the string class, passing objects to functions, arrays of objects, instance and static members, and designing classes. The objectives are to process strings, develop functions that take object arguments, store and process objects in arrays, distinguish between instance and static variables/functions, define constant functions, explore object-oriented vs procedural paradigms, design classes for BMI, composition relationships, stacks, and follow class design guidelines.

Uploaded by

Sujan Shrestha
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Chapter 10 Class Design

The document discusses class design in C++. It covers topics such as using the string class, passing objects to functions, arrays of objects, instance and static members, and designing classes. The objectives are to process strings, develop functions that take object arguments, store and process objects in arrays, distinguish between instance and static variables/functions, define constant functions, explore object-oriented vs procedural paradigms, design classes for BMI, composition relationships, stacks, and follow class design guidelines.

Uploaded by

Sujan Shrestha
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 49

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

The C++ string Class

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

Functions at, clear, erase, and empty


You can use the at(index) function to retrieve a character at a specified index, clear() to clear the string, erase(index, n) to delete part of the string, and empty() to test if a string is empty. For example, see the following code: string s1("Welcome"); cout << s1.at(3) << endl; // s1.at(3) returns c cout << s1.erase(2, 3) << endl; // s1 is now Weme s1.clear(); // s1 is now empty cout << s1.empty() << endl; // s1.empty returns 1 (means true)
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

Inserting and Replacing Strings


Here are the examples to use the insert and replace functions:
string s1("Welcome to HTML"); s1.insert(11, "C++ and "); cout << s1 << endl; // s1 becomes Welcome to C++ and HTML string s2("AA"); s2.insert(1, 4, 'B'); cout << s2 << endl; // s2 becomes to ABBBBA string s3("Welcome to HTML"); s3.replace(11, 4, "C++"); cout << s3 << endl; // returns Welcome to C++
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200

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

Passing Objects to Functions


You can pass objects by value or by reference.
c: Circle
radius: 5.0

c is an alias for myCircle

Copy myCircle to c myCircle: Circle


radius: 5.0

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

Improving Deck of Cards Solution


7.2.7 presented a program that picks four cards randomly from a deck of 52 cards. The program uses two functions displayRank and displaySuit to display a rank and a suit. These two functions can be replaced by defining the ranks and suits in two arrays of strings.

DeckOfCards
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200

Run
17

Instance and Static Members


instantiate circle1 radius = 1 numberOfObjects = 2 Memory 1 radius

Circle
-radius: double -numberOfObjects: int

2 +getNumberOfObjects(): int +getArea(): double instantiate circle2 radius = 5 numberOfObjects = 2 5

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

Use Class Name


Use ClassName::functionName(arguments) to invoke a static function and ClassName::staticVariable. This improves readability because the user can easily recognize the static function and data in the class.

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

Constant Member Functions


You can use the const keyword to specify a constant parameter to tell the compiler that the parameter should not be changed in the function. C++ also enables you to specify a constant member function to tell the compiler that the function should not change the value of any data fields in the object. To do so, place the const keyword at the end of the function header.
Circle4.h Circle4.cpp
21

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

The BMI Class


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

UseBMIClass

Run
23

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200

Example: The Course Class


Course -name: String -students: String[] -numberOfStudents: int +Course(name: String) +getName(): String The name of the course. The students who take the course. The number of students (default: 0). Creates a Course with the specified name. Returns the course name.

+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

Example: The StackOfIntegers Class


StackOfIntegers -elements: int[] -size: int +StackOfIntegers() +StackOfIntegers(capacity: int) +empty(): boolean +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 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

Designing the StackOfIntegers Class


Data1 Data2 Data3 Data3 Data2 Data1

Data1

Data2 Data1

Data3 Data2 Data1

Data2

Data1

Data1

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200

26

Implementing StackOfIntegers Class


elements[capacity 1]

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

The StackOfInteger Class


A stack is a data structure that holds objects in a last-in first-out fashion, as illustrated in Figure 10.10. It has many applications. For example, the compiler uses a stack to process function invocations. When a function is invoked, the parameters and local variables of the function are pushed into a stack. When a function calls another function, the new functions parameters and local variables are pushed into the stack. When a function finishes its work and returns to its caller, its associated space is released from the stack.

Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved. 0136097200

32

The StackOfInteger Class


Data1 Data2 Data3 Data3 Data2 Data1 Data1

Data1 Data3 Data2

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

Software Development Process


Requirement Specification System Analysis System Design

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

The process of designing the systems components.

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

Deployment makes the project available for use.

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

Maintenance is concerned with changing and improving the product.

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

Designing a Class: Cohesion


A

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

Designing a Class: Consistency


Follow

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

Designing a Class: Encapsulation


A

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

Designing a Class: Clarity

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

Designing a Class: Completeness


Classes

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

Designing a Class: Instance vs. Static

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

You might also like