Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 1.

Similar presentations


Presentation on theme: "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 1."— Presentation transcript:

1 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 1

2 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter Introduction to Classes 13

3 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Procedural and Object-Oriented Programming 13.1

4 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 4 Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a program Object-Oriented programming is based on the data and the functions that operate on it. Objects are instances of Abstract Data Types (ADTs) that represent the data and its functions

5 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 5 Procedural Programming Typically, data is stored in a collection of variables and/or structures, coupled with a set of functions that perform operations on the data The data and the functions are separate entities

6 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 6 Procedural Programming Example Write a C++ program to calculate the area of a rectangle Variables: Functions: double widthHolds the rectangle’s width double lengthHolds the rectangle’s length double areaHolds the rectangle’s area setData()Stores values in width and length calculateArea(double, double)Calculates the area of the rectangle displayWidth(double)Displays the width of the rectangle diaplayLength(double)Displays the length of the rectangle displayArea(double)Displays the area of the rectangle

7 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 7 Procedural Programming Example //calculate the area of a ractangle …. void setData(); double calculateArea(double, double); void displayWidth(double); void diaplayLength(double); void displayArea(double); int main() { double width; double length; double area; …… } Data and functions are separate

8 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 8 Limitations of Procedural Programming If the data structures change, many functions must also be changed data structure: way of storing data in computer, e.g. array, structs etc. Programs that are based on complex function hierarchies are: difficult to understand and maintain functions must be designed with those variables and their data structure in mind difficult to modify and extend easy to break

9 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 9 Introducing to Classes: Review on C++ Struct Structure: C++ construct that allows multiple variables to be grouped together General Format: struct { type1 field1; type2 field2;... };

10 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 10 Example struct Declaration: struct Student { int studentID; string name; short yearInSchool; double gpa; }; structure tag structure members Student bill; Define a Student Struct Varaible:

11 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 11 A Complete Program Using C++ Struct

12 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 12 Program (Continued)

13 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 13

14 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 14 Questions on Struct Look at the following structure declaration. struct Employee { char name[25]; int idNum; }; In this declaration, Employee is A).a memberC).a tag B).an arrayD).None of these

15 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 15 Questions on Struct (Cont.) Before a structure variable can be created, the structure must be ________. A) allocated B) declared C) initialized D) all of the above E) none of the above

16 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 16 Questions on Struct A program includes the following two structure declarations: If package is a variable of a Box structure, which of the following statements will display package's length? A) cout << package.length; B) cout << Box.size.length; C) cout << package.Dimension.length; D) cout << Box.Dimension.length; E) one of the above struct Dimension { int length, width; }; struct Box { char type; string color; Dimension size; };

17 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Introduction to Classes 13.2,4,5,6

18 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 18 Object-Oriented Programming Terminology All OOP languages have the following concepts, although the terms they use may differ: classes, object type, factory object instances, objects message passing, method lookup, member function invocation, method binding methods, member function, method function inheritance, subclassing

19 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 19 Object-Oriented Programming Terminology class: like a struct allows bundling of related variables (member data) and the functions that operate on them (member functions) describes the properties that all instances of the class will have it is a new data type you create that is more complex than the basic data types

20 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 20 Object-Oriented Programming Terminology object: like an instance of a struct an object is an instance of a class a class is a category of objects

21 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 21 Classes and Objects A Class is like a blueprint and objects are like houses built from the blueprint

22 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 22 Object-Oriented Programming Terminology attributes: members of a class methods or behaviors: member functions of a class

23 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 23 More on Objects data hiding: restricting access to certain members of an object public interface: members of an object that are available outside of the object this allows the object to provide access to some data and functions without sharing its internal details and design provides some protection from data corruption

24 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 24 Introduction to Classes A class declaration describes the member variables and member functions that its objects will have It is a pattern for creating objects, i.e. Objects are created from a class Format: class ClassName { declaration; };

25 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 25 Class Declaration Attributes Member functions (e.g., Accessors and Mutators) Access specifiers (e.g., public and private) Constructors/Destructors

26 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 26 Class Declaration Example class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; };

27 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 27 Class Attributes Similar to the members of a C++ struct Also known as data members, or data fields, or class properties For example, the properties of a student may include student ID, name, GPA, address, etc. Attributes class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; };

28 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 28 Class Member Functions Member functions are functions defined to manipulate class attributes Member Functions class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; };

29 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 29 Defining Member Functions There are two ways to define a member function: One: can place just the function prototype inside the class declaration and write the function definition after the class In the function definition, precede function name with class name and scope resolution operator (::) class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; }; void Rectangle::setWidth(double w) { width = w;} Declaration Section Implementation Section Note: These two sections should be placed into two different files

30 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 30 Defining Member Functions There are two ways to define a member function: Two: Can place entire function definition inside the class declaration class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double w) { width = w; } void setLength(double); double getWidth() const; double getLength() const; double getArea() const; }; Note: Member functions defined inside the class declaration are called inline functions; Only very short functions, like the one below, should be inline functions; inline function

31 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 31 Tradeoffs of Inline vs. Regular Member Functions When a regular function is called, control passes to the called function the compiler stores return address of call, allocates memory for local variables, etc. Code for an inline function is copied into the program in place of the call larger executable program, but no function call overhead, possibly faster execution

32 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 32 Separating class declaration, member function definitions, and program that uses the class into separate files is considered good design

33 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 33 Separating Specification from Implementation Place class declaration in a header file that serves as the class specification file. Name the file ClassName.h, for example, Rectangle.h Place member function definitions in ClassName.cpp, for example, Rectangle.cpp File should #include the class specification file Programs that use the class must #include the class specification file, and be compiled and linked with the member function definitions

34 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 34 Accessors and Mutators Mutator: a member function that stores a value in a private member variable, or changes its value in some way Accessor: function that retrieves a value from a private member variable. Accessors do not change an object's data, so they should be marked const.

35 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 35 Accessors and Mutators Example class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; }; Mutators Accessors

36 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 36 Using const With Member Functions const appearing after the parentheses in a member function declaration specifies that the function will not change any data in the calling object.

37 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 37 Access Specifiers (Public, Private) Used to control access to members of the class public: can be accessed by functions outside of the class private: can only be called by or accessed by functions that are members of the class

38 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 38 Class Example Private Members Public Members class Rectangle { private: double width; double length; public: Rectangle(double, double); void setWidth(double); void setLength(double); double getWidth() const; double getLength() const; double getArea() const; };

39 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 39 More on Access Specifiers Can be listed in any order in a class Can appear multiple times in a class If not specified, the default is private

40 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 40 Why Have Private Members? Making data members private provides data protection Data can be accessed only through public functions Public functions define the class’s public interface

41 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 41 Typically in object-oriented technology All the data fields should be private All the methods that are accessible by other should be public

42 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Constructors 13.7

43 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 43 Constructors Member function that is automatically called when an object is created Purpose is to construct an object Constructor function name is class name Has no return type

44 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 44

45 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 45 Continues...

46 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 46 Contents of Rectangle.ccp Version3 (continued)

47 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 47

48 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 48 Default Constructors A default constructor is a constructor that takes no arguments. If you write a class with no constructor at all, C++ will write a default constructor for you, one that does nothing. A simple instantiation of a class (with no arguments) calls the default constructor: Rectangle r;

49 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Passing Arguments to Constructors 13.8

50 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 50 Passing Arguments to Constructors To create a constructor that takes arguments: indicate parameters in prototype: Rectangle(double, double); Use parameters in the definition: Rectangle::Rectangle(double w, double len) { width = w; length = len; }

51 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 51 Passing Arguments to Constructors You can pass arguments to the constructor when you create an object: Rectangle r(10, 5);

52 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 52 More About Default Constructors If all of a constructor's parameters have default arguments, then it is a default constructor. For example: Rectangle(double = 0, double = 0); Creating an object and passing no arguments will cause this constructor to execute: Rectangle r;

53 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 53 Classes with No Default Constructor When all of a class's constructors require arguments, then the class has NO default constructor. When this is the case, you must pass the required arguments to the constructor when creating an object.

54 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Overloading Constructors 13.10

55 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 55 //class declaration class Student { private: int idNum; string name; double gradePointAverage; public: Student(); Student(int); Student(int, string); Student(int, string, double); …… };

56 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 56 //implementation section Student::Student() {idNum = 9999; name = “J. Smith”; gradePointAverage = 0.0; } Student::Student(int id) {idNum = id; } …… Student::Student(int id, string nm, double grade) {idNum = id; name = nm; gradePointAverage = grade; }

57 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 57 Function Overloading Two or more functions may have the same name, as long as their parameter lists are different.

58 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 58 Overloading Constructors A class can have more than one constructor Overloaded constructors in a class must have different parameter lists: Rectangle(); Rectangle(double); Rectangle(double, double);

59 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 59 From InventoryItem.h (Version 2)

60 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 60 From InventoryItem.h (Version 2)

61 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 61 From InventoryItem.h (Version 2)

62 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 62 Member Function Overloading Non-constructor member functions can also be overloaded: void setCost(double); void setCost(char *); Must have unique parameter lists as for constructors

63 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Destructors 13.9

64 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 64 Destructors Member function automatically called when an object is destroyed Destructor name is ~ classname, e.g., ~Rectangle Has no return type; takes no arguments Only one destructor per class, i.e., it cannot be overloaded If constructor allocates dynamic memory, destructor should release it

65 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 65

66 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 66 Contents of InventoryItem.h Version1 (Continued)

67 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 67

68 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 68

69 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 69 Only One Default Constructor and One Destructor Do not provide more than one default constructor for a class: one that takes no arguments and one that has default arguments for all parameters Square(); Square(int = 0); // will not compile Since a destructor takes no arguments, there can only be one destructor for a class

70 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 70 Constructors, Destructors, and Dynamically Allocated Objects When an object is dynamically allocated with the new operator, its constructor executes: Rectangle *r = new Rectangle(10, 20); When the object is destroyed, its destructor executes: delete r;

71 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 71 Programming Exercise Write a class definition for a Date class that contains three private integer data members: month, day, and year. Create two constructors for the class: one is the default constructor to set the Date as 1/1/2000, another one can take three arguments in to set the three part of the Date. Write mutators and accessors for the three data members. Here are some rules regarding set the three data members: if a month is greater than 12, set it to 12;if a day is greater than 31, then set it to 31. If negative values in, set them to 0. Finally, write a function to display the three data members of Date together. Write a main() function to instantiate a Date object and ask the user to set its month, day and year, then display the Date info to the user.

72 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Defining an Instance of a Class 13.3

73 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 73 Defining an Instance of a Class An object is an instance of a class Defined like structure variables: Rectangle r; Access members using dot operator: r.setWidth(5.2); cout << r.getWidth(); Compiler error if attempt to access private member using dot operator

74 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 74

75 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 75 Program 13-1 (Continued)

76 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 76 Program 13-1 (Continued)

77 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 77 Program 13-1 (Continued)

78 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 78 Avoiding Stale Data Some data is the result of a calculation. In the Rectangle class the area of a rectangle is calculated. length x width If we were to use an area variable here in the Rectangle class, its value would be dependent on the length and the width. If we change length or width without updating area, then area would become stale. To avoid stale data, it is best to calculate the value of that data within a member function rather than store it in a variable.

79 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 79 Pointer to an Object Can define a pointer to an object: Rectangle *rPtr; Can access public members via pointer: rPtr = &otherRectangle; rPtr->setLength(12.5); cout getLength() << endl;

80 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 80 Dynamically Allocating an Object We can also use a pointer to dynamically allocate an object.

81 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Private Member Functions 13.11

82 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 82 Using Private Member Functions A private member function can only be called by another member function It is used for internal processing by the class, not for use outside of the class See the createDescription function in InventoryItem.h (Version 3)

83 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 83 //class declaration class Student { private: int idNum; string name; double gradePointAverage; void changeGPA(double); public: Student(); void setID(int); void setName(string); void SetGPA(double); …… };

84 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 84 //using Student class int main() { Student John; …… John.changeGPA(someValue); …… } //implementation section ….. Student::setGPA(double gpa) {changeGPA(gpa); } ERROR

85 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 85 An object is ______ A. A category of classes B. A name given to a class C. An instance of a class D. The same as a class

86 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 86 Object is to class as ____ A. Library is to book B. Mother is to daughter C. Plato is to philosopher D. President is to Lincoln

87 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 87 What type of method/function is used to instantiate/create an object? A. mutator B. selector C. constructor D. accessor

88 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays of Objects 13.12

89 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 89 Arrays of Objects Objects can be the elements of an array: InventoryItem inventory[40]; Default constructor for object is used when array is defined

90 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 90 Arrays of Objects Must use initializer list to invoke constructor that takes arguments: InventoryItem inventory[3] = { "Hammer", "Wrench", "Pliers" };

91 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 91 Arrays of Objects If the constructor requires more than one argument, the initializer must take the form of a function call:

92 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 92 Arrays of Objects It isn't necessary to call the same constructor for each object in an array:

93 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 93 Accessing Objects in an Array Objects in an array are referenced using subscripts Member functions are referenced using dot notation: inventory[2].setUnits(30); cout << inventory[2].getUnits();

94 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 94

95 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 95 Program 13-3 (Continued)

96 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 96 C++ Invariants, Function Preconditions and Postconditions Contract Programming Contract programming is about specifying the design, in terms of the behavior, of your components (functions and classes), and asserting truths about the design of your code in the form of runtime tests placed within it.

97 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 97 The behavior is specified in terms of function/method preconditions, function/method postconditions, and class invariants. Preconditions state what conditions must be true in order for the function/method to perform according to its design. Postconditions say what conditions will exist after the function/method has performed according to its design.

98 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 98 Class invariants state what conditions hold true for the class to be in a state in which it can perform according to its design. Class invariants should be verified after construction, before destruction, and before and after the call of every public member function.

99 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 99 Example char *strcpy (char *dest, char const *src) { char *const r = dest; for(;; ++dest, ++src) { if( ‘\0’ == (*dest = *src)) { break; } return r; }

100 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 100 What are its pre-/post-conditions? Let N be the number of characters pointed to by src that do not contain the null-terminating character ‘\0’ Some preconditions are: src points to a sequence of N + 1 characters (type char) each of whose value is accessible by the expression *(src + n), where n is an integer in the range [0, N + 1) dest points to a block of memory that is writable for a length of N + 1 (or more) characters

101 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 101 Some postconditions are: For each n in the range [0, N + 1), the expression *(src + n) == *(dest + n) holds true The value returned is the value passed in the dest parameter

102 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 102 Preconditions char *strcpy(char *dest, char const *src) { char * r; /* Precondition checks */ assert(IsValidReadableString(src)); /* Is src valid? */ assert(IsValidWriteableMemory(dest, 1 + strlen(src))); /* Is dest valid? */ for (r = dest;; ++dest, ++src) { if(‘\0’ == (*dest = *src)) { break; } return r; }

103 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 103 Remarks assert() is the standard C macro that calls abort() if its expression evaluates false (0) IsValidReadableString() is a notional system call that tests to see if a pointer refers to a null-terminated string whose contents span read-accessible memory strlen() is the standard C function that returns the number of characters in a null-terminated string IsValidWriteableMemory() is a notional system call that tests that a pointer refers to a certain size of writeable memory.

104 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 104 Postconditions #if defined(ACMELIB_TEST_POSTCONDITIONS) static char *strcpy_impl(char *dest, char const *src); char *strcpy(char *dest, char const *src) { char *const d = dest; char const *const s = src; char *r; /* Precondition checks */ assert(IsValidReadableString(src)); assert(IsValidWriteableMemory(dest, 1 + strlen(src))); /* Call 'actual' function */ r = strcpy_impl(dest, src);

105 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 105 /* Postcondition checks. */ assert(0 == strcmp(d, s)); /* Are all contents the same? */ assert(r == d); /* Has it returned the right destination? */ return r; } static char *strcpy_impl(char *dest, char const *src) #else /* ? ACMELIB_TEST_POSTCONDITIONS */ char *strcpy(char *dest, char const *src) #endif /* ACMELIB_TEST_POSTCONDITIONS */ {... // Same impl as shown previously for strcpy() }

106 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 106 Remarks The reason for the separation into inner and outer functions is that the tests need to be outside the (inner) function context, in order to that the author of the tests can be confident that he/she is seeing the true post- condition This is especially important in C++ where the destructors of local scope objects might affect the post-conditions after their ostensibly ‘’final” test.

107 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 107 Class Invariants class Dollar { public: Dollar(int dollars, int cents); int getDollars() const; // returns # of dollars int getCents() const; // returns # of cents int getAsCents() const; // returns total amount in cents private: int m_dollars; int m_cents; };

108 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 108 We can say that the invariant for our Dollar class is that cents must not be more than 99. Hence we might write our invariant in the private member function is_valid(): class Dollar{... private: bool is_valid() const { if( m_cents 99) { return false; } return true; }... };

109 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 109 Somemethod() { assert(is_valid()); // Verify invariant on method entry //... assert(is_valid()); // Verify invariant on method exit return … }


Download ppt "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 13- 1."

Similar presentations


Ads by Google