Presentation is loading. Please wait.

Presentation is loading. Please wait.

611 18200 計算機程式語言 Lecture 09-1 國立台灣大學生物機電系 林達德 9 9 Classes: A Deeper Look, Part 1.

Similar presentations


Presentation on theme: "611 18200 計算機程式語言 Lecture 09-1 國立台灣大學生物機電系 林達德 9 9 Classes: A Deeper Look, Part 1."— Presentation transcript:

1 611 18200 計算機程式語言 Lecture 09-1 國立台灣大學生物機電系 林達德 9 9 Classes: A Deeper Look, Part 1

2 611 18200 計算機程式語言 Lecture 09-2 國立台灣大學生物機電系 林達德 9.1 Introduction 9.2 Time Class Case Study 9.3 Class Scope and Accessing Class Members 9.4 Separating Interface from Implementation 9.5 Access Functions and Utility Functions 9.6 Time Class Case Study: Constructors with Default Arguments 9.7 Destructors 9.8 When Constructors and Destructors Are Called 9.9 Time Class Case Study: A Subtle Trap—Returning a Reference to a private Data Member 9.10 Default Memberwise Assignment 9.11 Software Reusability

3 611 18200 計算機程式語言 Lecture 09-3 國立台灣大學生物機電系 林達德 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition errors caused by including more than one copy of a header file in a source-code file. To understand class scope and accessing class members via the name of an object, a reference to an object or a pointer to an object. To define constructors with default arguments. How destructors are used to perform "termination housekeeping" on an object before it is destroyed. When constructors and destructors are called and the order in which they are called. The logic errors that may occur when a public member function of a class returns a reference to private data. To assign the data members of one object to those of another object by default memberwise assignment.

4 611 18200 計算機程式語言 Lecture 09-4 國立台灣大學生物機電系 林達德 9.1 Introduction Integrated Time class case study Preprocessor directives Class scope and the relationships among members of a class Constructor and destructor

5 611 18200 計算機程式語言 Lecture 09-5 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Time class definition Time class member functions Defining member functions outside the class definition; class scope Using class Time Looking ahead to composition and inheritance Object size

6 611 18200 計算機程式語言 Lecture 09-6 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Classes –Model objects Attributes (data members) Behaviors (member functions) –Defined using keyword class –Member functions Methods Invoked in response to messages Member access specifiers –public: Accessible wherever object of class in scope –private: Accessible only to member functions of class –protected:

7 611 18200 計算機程式語言 Lecture 09-7 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Constructor function –Special member function Initializes data members Same name as class –Called when object instantiated –Several constructors Function overloading –No return type

8 611 18200 計算機程式語言 Lecture 09-8 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Objects of class –After class definition Class name new type specifier –C++ extensible language Object, array, pointer and reference declarations –Example: Time sunset; // object of type Time Time arrayOfTimes[ 5 ]; // array of Time objects Time *pointerToTime; // pointer to a Time object Time &dinnerTime = sunset; // reference to a Time object Class name becomes new type specifier.

9 611 18200 計算機程式語言 Lecture 09-9 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Member functions defined outside class –Binary scope resolution operator ( :: ) “Ties” member name to class name Uniquely identify functions of particular class Different classes can have member functions with same name –Format for defining member functions ReturnType ClassName::MemberFunctionName( ){ … } –Does not change whether function public or private Member functions defined inside class –Do not need scope resolution operator, class name –Compiler attempts inline Outside class, inline explicitly with keyword inline

10 611 18200 計算機程式語言 Lecture 09-10 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Destructors –Same name as class Preceded with tilde ( ~ ) –No arguments –Cannot be overloaded –Performs “termination housekeeping”

11 611 18200 計算機程式語言 Lecture 09-11 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Advantages of using classes –Simplify programming –Interfaces Hide implementation –Software reuse Composition (aggregation) –Class objects included as members of other classes Inheritance –New classes derived from old

12 Outline 611 18200 計算機程式語言 Lecture 09-12 國立台灣大學生物機電系 林達德 Time.h (1 of 1)

13 611 18200 計算機程式語言 Lecture 09-13 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study For clarity and readability, use each access specifier only once in a class definition. Place public members first, where they are easy to locate. Good Programming Practice 9.1

14 611 18200 計算機程式語言 Lecture 09-14 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Each element of a class should have private visibility unless it can be proven that the element needs public visibility. This is another example of the principle of least privilege. Software Engineering Observation 9.1

15 611 18200 計算機程式語言 Lecture 09-15 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Use #ifndef, #define and #endif preprocessor directives to form a preprocessor wrapper that prevents header files from being included more than once in a program. Error-Prevention Tip 9.1

16 611 18200 計算機程式語言 Lecture 09-16 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Use the name of the header file in upper case with the period replaced by an underscore in the #ifndef and #define preprocessor directives of a header file. Good Programming Practice 9.2

17 Outline 611 18200 計算機程式語言 Lecture 09-17 國立台灣大學生物機電系 林達德 Time.cpp (1 of 2)

18 Outline 611 18200 計算機程式語言 Lecture 09-18 國立台灣大學生物機電系 林達德 Time.cpp (2 of 2)

19 611 18200 計算機程式語言 Lecture 09-19 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Attempting to initialize a non -static data member of a class explicitly in the class definition is a syntax error. Common Programming Error 9.1

20 611 18200 計算機程式語言 Lecture 09-20 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Each sticky setting (such as a fill character or floating-point precision) should be restored to its previous setting when it is no longer needed. Failure to do so may result in incorrectly formatted output later in a program. Chapter 15, Stream Input/Output, discusses how to reset the fill character and precision. Error-Prevention Tip 9.2

21 611 18200 計算機程式語言 Lecture 09-21 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Defining a member function inside the class definition inlines the member function (if the compiler chooses to do so). This can improve performance. Performance Tip 9.1

22 611 18200 計算機程式語言 Lecture 09-22 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Defining a small member function inside the class definition does not promote the best software engineering, because clients of the class will be able to see the implementation of the function, and the client code must be recompiled if the function definition changes. Software Engineering Observation 9.2

23 611 18200 計算機程式語言 Lecture 09-23 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Only the simplest and most stable member functions (i.e., whose implementations are unlikely to change) should be defined in the class header. Software Engineering Observation 9.3

24 611 18200 計算機程式語言 Lecture 09-24 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Using an object-oriented programming approach can often simplify function calls by reducing the number of parameters to be passed. This benefit of object-oriented programming derives from the fact that encapsulating data members and member functions within an object gives the member functions the right to access the data members. Software Engineering Observation 9.4

25 611 18200 計算機程式語言 Lecture 09-25 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Member functions are usually shorter than functions in non- object-oriented programs, because the data stored in data members have ideally been validated by a constructor or by member functions that store new data. Because the data is already in the object, the member-function calls often have no arguments or at least have fewer arguments than typical function calls in non-object-oriented languages. Thus, the calls are shorter, the function definitions are shorter and the function prototypes are shorter. This facilitates many aspects of program development. Software Engineering Observation 9.5

26 611 18200 計算機程式語言 Lecture 09-26 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study The fact that member function calls generally take either no arguments or substantially fewer arguments than conventional function calls in non- object-oriented languages reduces the likelihood of passing the wrong arguments, the wrong types of arguments or the wrong number of arguments. Error-Prevention Tip 9.3

27 611 18200 計算機程式語言 Lecture 09-27 國立台灣大學生物機電系 林達德 9.2 Time Class Case Study Objects contain only data, so objects are much smaller than if they also contained member functions. Applying operator sizeof to a class name or to an object of that class will report only the size of the class ’ s data members. The compiler creates one copy (only) of the member functions separate from all objects of the class. All objects of the class share this one copy. Each object, of course, needs its own copy of the class ’ s data, because the data can vary among the objects. The function code is nonmodifiable (also called reentrant code or pure procedure) and, hence, can be shared among all objects of one class. Performance Tip 9.2

28 611 18200 計算機程式語言 Lecture 09-28 國立台灣大學生物機電系 林達德 9.3 Class Scope and Accessing Class Members Class scope –Data members, member functions –Within class scope Class members –Immediately accessible by all member functions –Referenced by name –Outside class scope Referenced through handles –Object name, reference to object, pointer to object File scope – Nonmember functions

29 611 18200 計算機程式語言 Lecture 09-29 國立台灣大學生物機電系 林達德 9.3 Class Scope and Accessing Class Members Function scope –Variables declared in member function –Only known to function –Variables with same name as class-scope variables Class-scope variable “hidden” –Access with scope resolution operator ( :: ) ClassName::classVariableName –Variables only known to function they are defined in –Variables are destroyed after function completion

30 611 18200 計算機程式語言 Lecture 09-30 國立台灣大學生物機電系 林達德 9.3 Class Scope and Accessing Class Members Operators to access class members –Identical to those for struct s –Dot member selection operator (. ) Object Reference to object –Arrow member selection operator ( -> ) Pointers

31 Outline 611 18200 計算機程式語言 Lecture 09-31 國立台灣大學生物機電系 林達德 fig09_03.cpp (1 of 2)

32 Outline 611 18200 計算機程式語言 Lecture 09-32 國立台灣大學生物機電系 林達德 fig09_03.cpp (2 of 2)

33 611 18200 計算機程式語言 Lecture 09-33 國立台灣大學生物機電系 林達德 9.4 Separating Interface from Implementation Separating interface from implementation –Advantage Easier to modify programs –Disadvantage Header files –Portions of implementation Inline member functions –Hints about other implementation private members Can hide more with proxy class

34 611 18200 計算機程式語言 Lecture 09-34 國立台灣大學生物機電系 林達德 9.4 Separating Interface from Implementation Header files –Class definitions and function prototypes –Included in each file using class #include –File extension.h Source-code files –Member function definitions –Same base name Convention –Compiled and linked

35 611 18200 計算機程式語言 Lecture 09-35 國立台灣大學生物機電系 林達德 9.4 Separating Interface from Implementation Clients of a class do not need access to the class ’ s source code in order to use the class. The clients do, however, need to be able to link to the class ’ s object code (i.e., the compiled version of the class). This encourages independent software vendors (ISVs) to provide class libraries for sale or license. The ISVs provide in their products only the header files and the object modules. No proprietary information is revealed — as would be the case if source code were provided. The C++ user community benefits by having more ISV-produced class libraries available. Software Engineering Observation 9.6

36 Outline 611 18200 計算機程式語言 Lecture 09-36 國立台灣大學生物機電系 林達德 fig09_04.cpp (1 of 2)

37 Outline 611 18200 計算機程式語言 Lecture 09-37 國立台灣大學生物機電系 林達德 fig09_04.cpp (2 of 2)

38 611 18200 計算機程式語言 Lecture 09-38 國立台灣大學生物機電系 林達德 9.4 Separating Interface from Implementation Information important to the interface to a class should be included in the header file. Information that will be used only internally in the class and will not be needed by clients of the class should be included in the unpublished source file. This is yet another example of the principle of least privilege. Software Engineering Observation 9.7

39 611 18200 計算機程式語言 Lecture 09-39 國立台灣大學生物機電系 林達德 9.5 Access Functions and Utility Functions Access functions –public –Read/display data –Predicate functions Check conditions Utility functions (helper functions) –private –Support operation of public member functions –Not intended for direct client use

40 Outline 611 18200 計算機程式語言 Lecture 09-40 國立台灣大學生物機電系 林達德 salesPerson.h (1 of 1) Set access function performs validity checks. private utility function.

41 Outline 611 18200 計算機程式語言 Lecture 09-41 國立台灣大學生物機電系 林達德 salesPerson.cpp (1 of 3)

42 Outline 611 18200 計算機程式語言 Lecture 09-42 國立台灣大學生物機電系 林達德 salesPerson.cpp (2 of 3) Set access function performs validity checks.

43 Outline 611 18200 計算機程式語言 Lecture 09-43 國立台灣大學生物機電系 林達德 salesPerson.cpp (3 of 3) private utility function to help function printAnnualSales ; encapsulates logic of manipulating sales array.

44 Outline 611 18200 計算機程式語言 Lecture 09-44 國立台灣大學生物機電系 林達德 fig09_07.cpp (1 of 1)

45 611 18200 計算機程式語言 Lecture 09-45 國立台灣大學生物機電系 林達德 9.5 Access Functions and Utility Functions A phenomenon of object-oriented programming is that once a class is defined, creating and manipulating objects of that class often involve issuing only a simple sequence of member-function calls — few, if any, control statements are needed. By contrast, it is common to have control statements in the implementation of a class ’ s member functions. Software Engineering Observation 9.8

46 611 18200 計算機程式語言 Lecture 09-46 國立台灣大學生物機電系 林達德 9.6 Time Class Case Study: Constructors with Default Arguments Constructors –Can specify default arguments –Default constructors Defaults all arguments OR Explicitly requires no arguments Can be invoked with no arguments Only one per class

47 Outline 611 18200 計算機程式語言 Lecture 09-47 國立台灣大學生物機電系 林達德 Time.h (1 of 2)

48 Outline 611 18200 計算機程式語言 Lecture 09-48 國立台灣大學生物機電系 林達德 Time.h (2 of 2)

49 Outline 611 18200 計算機程式語言 Lecture 09-49 國立台灣大學生物機電系 林達德 Time.cpp (1 of 3)

50 Outline 611 18200 計算機程式語言 Lecture 09-50 國立台灣大學生物機電系 林達德 Time.cpp (2 of 3)

51 Outline 611 18200 計算機程式語言 Lecture 09-51 國立台灣大學生物機電系 林達德 Time.cpp (3 of 3)

52 611 18200 計算機程式語言 Lecture 09-52 國立台灣大學生物機電系 林達德 9.6 Time Class Case Study: Constructors with Default Arguments If a member function of a class already provides all or part of the functionality required by a constructor (or other member function) of the class, call that member function from the constructor (or other member function). This simplifies the maintenance of the code and reduces the likelihood of an error if the implementation of the code is modified. As a general rule: Avoid repeating code. Software Engineering Observation 9.9

53 611 18200 計算機程式語言 Lecture 09-53 國立台灣大學生物機電系 林達德 9.6 Time Class Case Study: Constructors with Default Arguments Any change to the default argument values of a function requires the client code to be recompiled (to ensure that the program still functions correctly). Software Engineering Observation 9.10

54 Outline 611 18200 計算機程式語言 Lecture 09-54 國立台灣大學生物機電系 林達德 fig09_10.cpp (1 of 3)

55 Outline 611 18200 計算機程式語言 Lecture 09-55 國立台灣大學生物機電系 林達德 fig09_10.cpp (2 of 3)

56 Outline 611 18200 計算機程式語言 Lecture 09-56 國立台灣大學生物機電系 林達德 fig09_10.cpp (3 of 3)

57 611 18200 計算機程式語言 Lecture 09-57 國立台灣大學生物機電系 林達德 9.6 Time Class Case Study: Constructors with Default Arguments A constructor can call other member functions of the class, such as set or get functions, but because the constructor is initializing the object, the data members may not yet be in a consistent state. Using data members before they have been properly initialized can cause logic errors. Common Programming Error 9.2

58 611 18200 計算機程式語言 Lecture 09-58 國立台灣大學生物機電系 林達德 9.7 Destructors Destructors –Special member function –Same name as class Preceded with tilde ( ~ ) –No arguments –No return value –Cannot be overloaded –Performs “termination housekeeping” Before system reclaims object’s memory –Reuse memory for new objects –No explicit destructor Compiler creates “empty” destructor”

59 611 18200 計算機程式語言 Lecture 09-59 國立台灣大學生物機電系 林達德 9.7 Destructors It is a syntax error to attempt to pass arguments to a destructor, to specify a return type for a destructor (even void cannot be specified), to return values from a destructor or to overload a destructor. Common Programming Error 9.3

60 611 18200 計算機程式語言 Lecture 09-60 國立台灣大學生物機電系 林達德 9.7 Destructors As we will see in the remainder of the book, constructors and destructors have much greater prominence in C++ and object-oriented programming than is possible to convey after only our brief introduction here. Software Engineering Observation 9.11

61 611 18200 計算機程式語言 Lecture 09-61 國立台灣大學生物機電系 林達德 9.8 When Constructors and Destructors Are Called Constructors and destructors –Called implicitly by compiler Order of function calls –Depends on order of execution When execution enters and exits scope of objects –Generally, destructor calls reverse order of constructor calls

62 611 18200 計算機程式語言 Lecture 09-62 國立台灣大學生物機電系 林達德 9.8 When Constructors and Destructors Are Called Order of constructor, destructor function calls –Global scope objects Constructors –Before any other function (including main ) Destructors –When main terminates (or exit function called) –Not called if program terminates with abort –Automatic local objects Constructors –When objects defined Each time execution enters scope Destructors –When objects leave scope Execution exits block in which object defined –Not called if program ends with exit or abort

63 611 18200 計算機程式語言 Lecture 09-63 國立台灣大學生物機電系 林達德 9.8 When Constructors and Destructors Are Called Order of constructor, destructor function calls –static local objects Constructors –Exactly once –When execution reaches point where object defined Destructors –When main terminates or exit function called –Not called if program ends with abort

64 Outline 611 18200 計算機程式語言 Lecture 09-64 國立台灣大學生物機電系 林達德 CreateAndDestroy.h (1 of 1) Constructor and destructor member functions. private members to show order of constructor, destructor function calls.

65 Outline 611 18200 計算機程式語言 Lecture 09-65 國立台灣大學生物機電系 林達德 CreateAndDestroy.cpp (1 of 1) Output message to demonstrate timing of constructor function calls.

66 Outline 611 18200 計算機程式語言 Lecture 09-66 國立台灣大學生物機電系 林達德 Fig09_13.cpp (1 of 3) Create variable with global scope. Create local automatic object. Create static local object. Create local automatic objects. Create local automatic object.

67 Outline 611 18200 計算機程式語言 Lecture 09-67 國立台灣大學生物機電系 林達德 fig09_13.cpp (2 of 3) Create local automatic object in function. Create static local object in function. Create local automatic object in function.

68 Outline 611 18200 計算機程式語言 Lecture 09-68 國立台灣大學生物機電系 林達德 fig09_13.cpp (3 of 3)

69 611 18200 計算機程式語言 Lecture 09-69 國立台灣大學生物機電系 林達德 9.9 Time Class Case Study: A Subtle Trap— Returning a Reference to a private Data Member Reference to object –Alias for name of object –Lvalue Can receive value in assignment statement –Changes original object Returning references –public member functions can return non- const references to private data members Client able to modify private data members

70 Outline 611 18200 計算機程式語言 Lecture 09-70 國立台灣大學生物機電系 林達德 Time.h (1 of 1) Function to demonstrate effects of returning reference to private data member.

71 Outline 611 18200 計算機程式語言 Lecture 09-71 國立台灣大學生物機電系 林達德 Time.cpp (1 of 2)

72 Outline 611 18200 計算機程式語言 Lecture 09-72 國立台灣大學生物機電系 林達德 Time.cpp (2 of 2) Return reference to private data member hour.

73 Outline 611 18200 計算機程式語言 Lecture 09-73 國立台灣大學生物機電系 林達德 Fig09_16.cpp (1 of 2) badSetHour returns reference to private data member hour. Reference allows setting of private data member hour.

74 Outline 611 18200 計算機程式語言 Lecture 09-74 國立台灣大學生物機電系 林達德 Fig09_16.cpp (2 of 2) Can use function call as lvalue to set invalid value. Returning reference allowed invalid setting of private data member hour.

75 611 18200 計算機程式語言 Lecture 09-75 國立台灣大學生物機電系 林達德 9.9 Time Class Case Study: A Subtle Trap— Returning a Reference to a private Data Member Returning a reference or a pointer to a private data member breaks the encapsulation of the class and makes the client code dependent on the representation of the class ’ s data. So, returning pointers or references to private data is a dangerous practice that should be avoided. Error-Prevention Tip 9.4

76 611 18200 計算機程式語言 Lecture 09-76 國立台灣大學生物機電系 林達德 9.10 Default Memberwise Assignment Assigning objects –Assignment operator ( = ) Can assign one object to another of same type Default: memberwise assignment –Each right member assigned individually to left member Passing, returning objects –Objects passed as function arguments –Objects returned from functions –Default: pass-by-value Copy of object passed, returned –Copy constructor Copy original values into new object

77 Outline 611 18200 計算機程式語言 Lecture 09-77 國立台灣大學生物機電系 林達德 Date.cpp (1 of 1)

78 Outline 611 18200 計算機程式語言 Lecture 09-78 國立台灣大學生物機電系 林達德 fig09_19.cpp (1 of 1) Default memberwise assignment assigns each member of date1 individually to each member of date2.

79 611 18200 計算機程式語言 Lecture 09-79 國立台灣大學生物機電系 林達德 9.10 Default Memberwise Assignment Passing an object by value is good from a security standpoint, because the called function has no access to the original object in the caller, but pass-by-value can degrade performance when making a copy of a large object. An object can be passed by reference by passing either a pointer or a reference to the object. Pass-by-reference offers good performance but is weaker from a security standpoint, because the called function is given access to the original object. Pass-by- const -reference is a safe, good- performing alternative (this can be implemented with a const reference parameter or with a pointer-to- const - data parameter). Performance Tip 9.3

80 611 18200 計算機程式語言 Lecture 09-80 國立台灣大學生物機電系 林達德 9.11 Software Reusability Software reusability –Class libraries Well-defined Carefully tested Well-documented Portable Widely available –Speeds development of powerful, high-quality software Rapid applications development (RAD) –Resulting problems Cataloging schemes Licensing schemes Protection mechanisms


Download ppt "611 18200 計算機程式語言 Lecture 09-1 國立台灣大學生物機電系 林達德 9 9 Classes: A Deeper Look, Part 1."

Similar presentations


Ads by Google