1 / 52

Class Features and Design Issues

Understand constructors in C++ classes, creating constructors, overloading constructors, class interaction, and overriding default values in constructors effectively.

tguenther
Télécharger la présentation

Class Features and Design Issues

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 6 Class Features and Design Issues Object-Oriented Programming Using C++ Second Edition

  2. 6 Objectives • In this chapter, you will learn: • How to classify the roles of member functions • How to create constructors • How to override constructor default values • How to overload constructors • How to use a class within another class

  3. 6 Objectives • In this chapter, you will learn: • How, why, and when to use the preprocessor directives #ifndef, #define, and #endif • Techniques for managing attributes and functions of classes • About coupling, and how to achieve loose coupling • About cohesion, and how to achieve high cohesion

  4. 6 Introducing Member Functions • You can create an infinite number of classes and write an infinite number of functions • You can classify the roles of member functions into four basic groups: • Inspector functions, also called access functions • Mutator functions, also known as implementors • Auxiliary functions, also known as facilitators • Manager functions

  5. 6 Understanding Constructors • A constructor is a function that is called automatically each time an object is created • You have been using constructors all along in your programs • When you declare a simple scalar variable, such as int number, C++ calls an internal constructor function that reserves a memory location of the correct size for an integer, and attaches the name “number” to that location • The definition into number = 23; calls a constructor that reserves memory, attaches a name, and assigns a value

  6. 6 Understanding Constructors • Until now, when you created class objects, you let C++ provide its own constructor for the objects • When an object is created, its data fields store whatever values (often called garbage values) happen to be in those positions in computer memory • After you instantiated objects in your programs, you used a mutator function with a name such as setValues() to assign useful values to data members

  7. 6 Understanding Constructors • That process is similar to declaring a variable and assigning a value to it later • However, you might want to initialize one or more of an object’s data members immediately upon creation • When you want to initialize an object, or perform other tasks when the object is created, then you must write your own constructor for the class

  8. 6 Writing Your Own Constructors • Constructor functions differ from other member functions in two ways: • You must give a constructor function the same name as the class for which it is a constructor • You cannot give a constructor function a return type (it’s not necessary because constructors always return an object of the class to which they belong) • A constructor must have the same name as its class because the constructor is called automatically when an object is created

  9. 6 Writing Your Own Constructors • If you named a constructor something other than its class name, C++ would not know it was a constructor • Constructor functions are not coded with a return type

  10. 6 Writing Your Own Constructors • The constructor function Employee() shown in Figure 6-2 is called a default constructor because it does not require any arguments

  11. 6 Employee Class and main() Function that Instantiates an Employee EX6-1

  12. 6 Writing Your Own Constructors • A constructor that requires no arguments is a default constructor, regardless of whether the constructor has an empty argument list or an argument list in which a default value is provided for each argument

  13. 6 Employee Class with Constructor that Uses Default Arguments EX6-2

  14. 6 Writing Your Own Constructors EX6-3 • In the set of steps on pages 201 to 203 of the textbook, you create a class named Pizza • A constructor sets the default Pizza to cheese topping and a 12-inch size

  15. 6 Overriding the Constructor’s Default Arguments • To replace the default values assigned by a constructor, you can use a mutator function such as setValues() • You also can override a constructor’s default values by passing arguments to the constructor when you instantiate an object • Two rules apply to the use of default parameters with constructor functions: • If you want to override constructor default values for an object you are instantiating, you also must override all parameters to the left of that value • If you omit any constructor argument when you instantiate an object, you must use default values for all parameters to the right of that argument

  16. 6 Overriding the Constructor’s Default Arguments • The result of the three instantiations is as follows: • An assistant with the default ID of 9999, an an hourly rate of 5.65 • A clerk whose 1111 ID overrides the default idNumber, but whose hourly rate is the default 5.65 • A driver show 2222 ID and hourly rate of 18.95 both override the default values in the constructor

  17. 6 Overriding the Constructor’s Default Arguments • In the set of steps on page 204 of the textbook, you write a main() function that instantiates several objects of the Pizza class you defined earlier • You also create objects that use all, some, and none of the constructor default values

  18. 6 Overloading Constructors • Just like other C++ functions, constructors can be overloaded • Overloading a function name allows you to use the same name for separate functions that have different argument lists • Constructor functions for a given class must all have the same name as their class • If you provide two or more constructors for the same class, they are overloaded by definition • The program shown in Figure 6-10 uses the Employee class shown in Figure 6-9 • Figure 6-11 shows the output of a typical execution

  19. 6 Employee Class with Overloaded Constructors EX6-4

  20. 6 Overloading Constructors

  21. 6 Overloading Constructors Stop here EX6-5 • In the steps referred to on pages 207 to 209 of the textbook, you create a Graduate class with three overloaded constructors— one each for a Graduate with one, two, or three college degrees • Each constructor requires the Graduate’s last name and computes the Graduate’s debt based on the number of degrees obtained

  22. 6 Using Destructors • A destructor is a function that is called automatically each time an object is destroyed • An object is destroyed when it goes out of scope • The rules for creating destructor function prototypes are similar to the rules for constructor function prototypes • As with constructors, you must give a destructor function the same name as its class ( and therefore the same name as any constructor for that class) • As with constructors, you cannot give a destructor function a return type • Unlike constructors, you cannot pass any values to a destructor

  23. 6 Using Destructors • A destructor must have the same name as its class (plus the tilde) because it is called automatically when an object is destroyed • Only one destructor can exist for each class • The Object class in Figure 6-13 contains one field, a constructor, and a destructor

  24. 6 Using Destructors

  25. 6 Using Destructors

  26. 6 Using Classes within Classes • On many occasions you might want to use a class within another class • Just as you build any complex real-life item, such as an automobile, from other well-designed parts, complex classes are easier to create if you use previously written, well-designed classes as components • Figure 6-18 shows a simple Inventory class that a store could use to hold stock numbers and prices of items for sale • Figure 6-19 shows a Salesperson class

  27. 6 The InventoryItem Class

  28. 6 The Salesperson Class

  29. 6 Using Classes within Classes • Figure 6-20 shows a Transaction class • To represent a sales transaction, you want to include information about the item sold and the salesperson who sold it • You could write a transaction class that contained individual fields, such as item stock number and salesperson ID number, but it is more efficient to reuse the InventoryItem and Salesperson classes that are already created and tested

  30. 6 The Transaction Class

  31. 6 Considering Reusability and Maintenance Issues • Reusability is a major focus of thinking in an object-oriented manner • Creating self-contained components such as InventoryItem that you include in other classes makes program maintenance easier • More than half of most programmers time on the job (and almost all of new programmers’ time) is spent maintaining or changing existing programs • The more places a change must be made, the more time it takes, the more likely that an error occurs when that change is made, and the greater the change that one of the necessary changes is overlooked

  32. 6 Considering Reusability and Maintenance Issues

  33. 6 Using #IFNDEF, #DEFINE, and #ENDIF • After you have created a collection of useful classes, often called a library, you might find that many class files contain the same #include statement • Using the #define directive alone does not provide much benefit • Instead, it is usually coupled with two other directives #ifndef and #endif • The C++ directive #ifndef allows you to test whether a class has already been defined in a project

  34. 6 Using #IFNDEF, #DEFINE, and #ENDIF • The #ifndef directive means “if not defined” • If you place an #ifndef at the beginning of a class, and the class has not been defined, then the #define directive will be implemented

  35. 6 Improving Functions • As you write larger and more complicated programs, be sure to spend time on planning and design • Each class you design must be well thought out • A final product is great only if each component is well designed—just ask anyone with a $30,000 car that leaks oil

  36. 6 Selecting Member Data and Function Names • When you begin to design a class and select its member functions, you need to consider the following questions: • Will special initialization tasks be necessary? • Will any special clean-up tasks be carried out when a class object goes out of scope? • Will class data members be assigned values after their construction?

  37. 6 Selecting Member Data and Function Names • C++ identifiers must not include spaces and cannot begin with a number, but you also must apply other general guidelines: • Use meaningful names • Use pronounceable names • Be judicious in your use of abbreviations • Avoid using digits in a name • Use capitalization freely in multi-word names • Include a form of “to be,” such as “is” or “are,” in names for variables that hold a status • Often a verb-noun provides a good combination for a function

  38. 6 Selecting Member Data and Function Names • Luckily, you do not have to write a C++ class or program completely before you can see whether the overall plan works • Most programmers use stubs during the initial phases of a project • Stubs are simple routines that do nothing (or very little); you incorporate them into a program as placeholders

  39. 6 Reducing Coupling Between Functions • Coupling is a measure of the strength of the connection between two functions; it expresses the extent to which information is exchanged by functions • Coupling is either tight coupling or loose coupling, depending on how much one function depends on information from another • Tight coupling, which features much dependence between functions, makes programs more prone to errors

  40. 6 Reducing Coupling Between Functions • There are many data paths to manage, many chances for bad data to pass from one function to another, and many chances for one function to alter information needed by another • Loose coupling occurs when functions do not depend on others • Usually, you can determine that coupling is occurring at one of several levels • Data coupling is the loosest type of coupling and, therefore, the most desirable

  41. 6 Reducing Coupling Between Functions • You can evaluate whether coupling between functions is loose or tight by looking at several characteristics: • The intimacy between functions • The number of parameters that are passed between functions • The visibility of accessed data in a function prototype • Data coupling occurs when functions share a data item by passing parameters • Data-structured coupling is similar to data coupling, but an entire data structure is passed from one function to another

  42. 6 Reducing Coupling Between Functions • Control coupling occurs when one function passes a parameter to another, controlling the other function or telling it what to do • You can easily reduce the coupling demonstrated in the whatToDo() function in Figure 6-25 in one of two ways

  43. 6 Reducing Coupling Between Functions • Eliminate the whatToDo() function, and let the functions that call whatToDo() call doFirstThing(), doSecondThing(), or doLastThing() on their own

  44. 6 Reducing Coupling Between Functions • Do not pass the choice variable to the whatToDo() function, but place the prompt and data entry for choice within the whatToDo() function where it is directly connected to the three possible outcomes • External coupling and common coupling occur when two or more functions access the same global variable or global data structure, respectively • Pathological coupling occurs when two or more functions change each other’s data

  45. 6 Increasing Cohesion within a Function • Cohesion refers to how well the operations in a function relate to one another • In highly cohesive functions, all operations are related • Functional cohesion occurs when all of the function operations contribute to the performance of only one task • The function square() is highly cohesive; it performs one simple task, squaring a number • Sequential cohesion arises when a function performs operations that must be carried out in a specific order, on the same data

  46. 6 Increasing Cohesion within a Function

  47. 6 Increasing Cohesion within a Function • Communicational cohesion occurs when functions contain statements that perform tasks that share data • The tasks are not related—just the data • Temporal cohesion arises when the tasks in a function are related by time • The prime examples of temporally cohesive functions in C++ classes are constructors and destructors

  48. 6 Increasing Cohesion within a Function • Procedural cohesion arises when, as with sequential cohesion, the tasks of a function are performed in sequence • It is acceptable to use procedural cohesion in main() functions • The main() function in the above example also can be called a dispatcher function, because it sends messages to a sequence of (supposedly) more cohesive functions

  49. 6 Increasing Cohesion within a Function • Logical cohesion arises when a member function performs one or many tasks depending on a decision, whether he decision takes the form of a switch statement or a series of if statements • Coincidental cohesion, as the name implies, is based on coincidence • The operations in a function just happen to be placed together • Obviously, this type of connection is the weakest form of cohesion and is considered undesirable

  50. 6 Summary • You can classify the roles of member functions into four basic groups: • Inspector — Mutator • Auxillary — Manager • A constructor is a function that is called automatically each time an object is created • If you want to override constructor default values for an object you are instantiating, you also must override all parameters to the left of that value • If you provide two or more constructors for the same class, they are overloaded by definition

More Related