Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 10 Defining Classes. Chapter 10 Defining Classes.

Similar presentations


Presentation on theme: "Chapter 10 Defining Classes. Chapter 10 Defining Classes."— Presentation transcript:

1

2 Chapter 10 Defining Classes

3 Abstraction in Software Development
Abstraction allows a programmer to design a solution to a problem and to use data items without concern for how the data items are implemented This has already been encountered in the book: To use the pow function, you need to know what inputs it expects and what kind of results it produces You do not need to know how it works

4 Abstraction and Data Types
Abstraction: a definition that captures general characteristics without details ex: An abstract triangle is a 3-sided polygon. A specific triangle may be scalene, isosceles, or equilateral Data Type: defines the kind of values that can be stored and the operations that can be performed on it

5 Abstraction and Data Types
Abstraction: a definition that captures general characteristics without details ex: An abstract triangle is a 3-sided polygon. A specific triangle may be scalene, isosceles, or equilateral Data Type: defines the kind of values that can be stored and the operations that can be performed on it

6 7.1 Abstract Data Types Structures/Classes that are defined by the operations that are performed by/on it. Have no implementation shared “interface contract” that the object provides

7 7.1 Abstract Data Types Programmer-created data types that specify
legal values that can be stored operations that can be done on the values The user of an abstract data type (ADT) does not need to know any implementation details (e.g., how the data is stored or how the operations on it are carried out)

8 Overview 10.1 Structures ---- Object Oriented Programming 10.2 Classes 10.3 Abstract Data Types 10.4 Introduction to Inheritance

9 10.1 Structures

10 Structures A structure can be viewed as an object
Contains no member functions (The structures used here have no member functions) Contains multiple values of possibly different types The multiple values are logically related as a single item Example: A bank Certificate of Deposit (CD) has the following values: a balance an interest rate a term (months to maturity)

11 Remember this semicolon!
The CD Definition The Certificate of Deposit structure can be defined as struct CDAccount { double balance; double interest_rate; int term; //months to maturity }; Keyword struct begins a structure definition CDAccount is the structure tag or the structure’s type Member names are identifiers declared in the braces Remember this semicolon!

12 Using the Structure Structure definition is generally placed outside any function definition This makes the structure type available to all code that follows the structure definition To declare two variables of type CDAccount: CDAccount my_account, your_account; My_account and your_account contain distinct member variables balance, interest_rate, and term

13 Specifying Member Variables
Member variables are specific to the structure variable in which they are declared Syntax to specify a member variable: Structure_Variable_Name . Member_Variable_Name Given the declaration: CDAccount my_account, your_account; Use the dot operator to specify a member variable my_account.balance my_account.interest_rate my_account.term

14 Using Member Variables
Member variables can be used just as any other variable of the same type my_account.balance = 1000; your_account.balance = 2500; Notice that my_account.balance and your_account.balance are different variables! my_account.balance = my_account.balance + interest; Display 10.1 (1) Display 10.1 (2) Display 10.2

15 Duplicate Names Member variable names duplicated between structure types are not a problem. super_grow.quantity and apples.quantity are different variables stored in different locations struct FertilizerStock { double quantity; double nitrogen_content; }; FertilizerStock super_grow; struct CropYield { int quantity; double size; }; CropYield apples;

16 Structures as Arguments
Structures can be arguments in function calls The formal parameter can be call-by-value The formal parameter can be call-by-reference Example: void get_data(CDAccount& the_account); Uses the structure type CDAccount we saw earlier as the type for a call-by-reference parameter

17 Structures as Return Types
Structures can be the type of a value returned by a function Example: CDAccount shrink_wrap(double the_balance, double the_rate, int the_term) { CDAccount temp; temp.balance = the_balance; temp.interest_rate = the_rate; temp.term = the_term; return temp; }

18 Assignment and Structures
The assignment operator can be used to assign values to structure types Using the CDAccount structure again: CDAccount my_account, your_account; my_account.balance = ; my_account.interest_rate = 5.1; my_account.term = 12; your_account = my_account; Assigns all member variables in your_account the corresponding values in my_account

19 Initializing Structures
A structure can be initialized when declared Example: struct Date { int month; int day; int year; }; Can be initialized in this way Date due_date = {12, 31, 2004};

20 Hierarchical Structures
Structures can contain member variables that are also structures struct PersonInfo contains a Date structure struct PersonInfo { double height; int weight; Date birthday; }; struct Date { int month; int day; int year; };

21 10.2 Classes

22 Classes A class is a data type whose variables are objects
The definition of a class includes Description of the kinds of values of the member variables Description of the member functions A class description is somewhat like a structure definition plus the member variables

23 Class Definitions A class definition includes
A description of the kinds of values the variable can hold A description of the member functions We will start by defining structures as a first step toward defining classes

24 What Is a Class? A class is a data type whose variables are objects
Some pre-defined data types you have used are int char A pre-defined class you have used is ifstream You can define your own classes as well

25 Introduction to Classes
Class declaration format: class className { declaration; }; Notice the required ;

26 Access Specifiers Used to control access to members of the class.
Each member is declared to be either public: can be accessed by functions outside of the class or private: can only be called by or accessed by functions that are members of the class

27 Class Example class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; Access specifiers

28 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

29 7.4 Creating and Using Objects
An object is an instance of a class It is defined just like other variables Square sq1, sq2; It can access members using dot operator sq1.setSide(5); cout << sq1.getSide(); See pr7-01.cpp

30 Types of Member Functions
Acessor, get, getter function: uses but does not modify a member variable ex: getSide Mutator, set, setter function: modifies a member variable ex: setSide

31 7.5 Defining Member Functions
Member functions are part of a class declaration Can place entire function definition inside the class declaration or Can place just the prototype inside the class declaration and write the function definition after the class

32 What Is a Class? A class is a data type whose variables are objects
Some pre-defined data types you have used are int char A pre-defined class you have used is ifstream You can define your own classes as well

33 Defining Member Functions Inside the Class Declaration
Member functions defined inside the class declaration are called inline functions Only very short functions, like the one below, should be inline functions int getSide() { return side; }

34 Inline Member Function Example
class Square { private: int side; public: void setSide(int s) { side = s; } int getSide() { return side; } }; inline functions

35 Defining Member Functions After the Class Declaration
Put a function prototype in the class declaration In the function definition, precede the function name with the class name and scope resolution operator (::) int Square::getSide() { return side; } See pr7-02.cpp and pr7-03.cpp

36 Conventions and a Suggestion
Member variables are usually private Accessor and mutator functions are usually public Use ‘get’ in the name of accessor functions, ‘set’ in the name of mutator functions Suggestion: calculate values to be returned in accessor functions when possible, to minimize the potential for stale data

37 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 when the program is compiled This makes alarger executable program, but There is less function call overhead, and possibly faster execution

38 A Class Example To create a new type named DayOfYear as a class definition Decide on the values to represent This example’s values are dates such as July 4 using an integer for the number of the month Member variable month is an int (Jan = 1, Feb = 2, etc.) Member variable day is an int Decide on the member functions needed We use just one member function named output

39 Class DayOfYear Definition
class DayOfYear { public: void output( ); int month; int day; }; Member Function Declaration

40 Defining a Member Function
Member functions are declared in the class declaration Member function definitions identify the class in which the function is a member void DayOfYear::output() { cout << “month = “ << month << “, day = “ << day << endl; }

41 Member Function Definition
Member function definition syntax: Returned_Type Class_Name::Function_Name(Parameter_List) { Function Body Statements } Example: void DayOfYear::output( ) { cout << “month = “ << month << “, day = “ << day << endl; }

42 The ‘::’ Operator ‘::’ is the scope resolution operator
Tells the class a member function is a member of void DayOfYear::output( ) indicates that function output is a member of the DayOfYear class The class name that precedes ‘::’ is a type qualifier

43 ‘::’ and ‘.’ ‘::’ used with classes to identify a member void DayOfYear::output( ) { // function body } ‘.’used with variables to identify a member DayOfYear birthday; birthday.output( );

44 Calling Member Functions
Calling the DayOfYear member function output is done in this way: DayOfYear today, birthday; today.output( ); birthday.output( ); Note that today and birthday have their own versions of the month and day variables for use by the output function Display 10.3 (1) Display 10.3 (2)

45 Encapsulation Encapsulation is
Combining a number of items, such as variables and functions, into a single package such as an object of a class

46 Problems With DayOfYear
Changing how the month is stored in the class DayOfYear requires changes to the program If we decide to store the month as three characters (JAN, FEB, etc.) instead of an int cin >> today.month will no longer work because we now have three character variables to read if(today.month == birthday.month) will no longer work to compare months The member function “output” no longer works

47 Ideal Class Definitions
Changing the implementation of DayOfYear requires changes to the program that uses DayOfYear An ideal class definition of DayOfYear could be changed without requiring changes to the program that uses DayOfYear

48 Fixing DayOfYear To fix DayOfYear
We need to add member functions to use when changing or accessing the member variables If the program never directly references the member variables, changing how the variables are stored will not require changing the program We need to be sure that the program does not ever directly reference the member variables

49 Public Or Private? C++ helps us restrict the program from directly referencing member variables private members of a class can only be referenced within the definitions of member functions If the program tries to access a private member, the compiler gives an error message Private members can be variables or functions

50 Private Variables Private variables cannot be accessed directly by the program Changing their values requires the use of public member functions of the class To set the private month and day variables in a new DayOfYear class use a member function such as void DayOfYear::set(int new_month, int new_day) { month = new_month; day = new_day; }

51 Public or Private Members
The keyword private identifies the members of a class that can be accessed only by member functions of the class Members that follow the keyword private are private members of the class The keyword public identifies the members of a class that can be accessed from outside the class Members that follow the keyword public are public members of the class

52 A New DayOfYear The new DayOfYear class demonstrated in Display 10.4…
Uses all private member variables Uses member functions to do all manipulation of the private member variables Member variables and member function definitions can be changed without changes to the program that uses DayOfYear Display 10.4 (1) Display 10.4 (2)

53 Using Private Variables
It is normal to make all member variables private Private variables require member functions to perform all changing and retrieving of values Accessor functions allow you to obtain the values of member variables Example: get_day in class DayOfYear Mutator functions allow you to change the values of member variables Example: set in class DayOfYear

54 General Class Definitions
The syntax for a class definition is class Class_Name { public: Member_Specification_1 Member_Specification_2 … Member_Specification_3 private: Member_Specification_n+1 Member_Specification_n+2 … };

55 Declaring an Object Once a class is defined, an object of the class is declared just as variables of any other type Example: To create two objects of type Bicycle: class Bicycle { // class definition lines }; Bicycle my_bike, your_bike;

56 The Assignment Operator
Objects and structures can be assigned values with the assignment operator (=) Example: DayOfYear due_date, tomorrow; tomorrow.set(11, 19); due_date = tomorrow;

57 Program Example: BankAccount Class
This bank account class allows Withdrawal of money at any time All operations normally expected of a bank account (implemented with member functions) Storing an account balance Storing the account’s interest rate Display 10.5 ( 1) Display 10.5 ( 3) Display 10.5 ( 2) Display 10.5 ( 4)

58 Calling Public Members
Recall that if calling a member function from the main function of a program, you must include the the object name: account1.update( );

59 Calling Private Members
When a member function calls a private member function, an object name is not used fraction (double percent); is a private member of the BankAccount class fraction is called by member function update void BankAccount::update( ) { balance = balance fraction(interest_rate)* balance; }

60 Constructors A constructor can be used to initialize member variables when an object is declared A constructor is a member function that is usually public A constructor is automatically called when an object of the class is declared A constructor’s name must be the name of the class A constructor cannot return a value No return type, not even void, is used in declaring or defining a constructor

61 Constructor Declaration
A constructor for the BankAccount class could be declared as: class BankAccount { public: BankAccount(int dollars, int cents, double rate); //initializes the balance to $dollars.cents //initializes the interest rate to rate percent …//The rest of the BankAccount definition };

62 Constructor Definition
The constructor for the BankAccount class could be defined as BankAccount::BankAccount(int dollars, int cents, double rate) { if ((dollars < 0) || (cents < 0) || ( rate < 0 )) { cout << “Illegal values for money or rate\n”; exit(1); } balance = dollars * cents; interest_rate = rate; } Note that the class name and function name are the same

63 Calling A Constructor (1)
A constructor is not called like a normal member function: BankAccount account1; account1.BankAccount(10, 50, 2.0);

64 Calling A Constructor (2)
A constructor is called in the object declaration BankAccount account1(10, 50, 2.0); Creates a BankAccount object and calls the constructor to initialize the member variables

65 Overloading Constructors
Constructors can be overloaded by defining constructors with different parameter lists Other possible constructors for the BankAccount class might be BankAccount (double balance, double interest_rate); BankAccount (double balance); BankAccount (double interest_rate); BankAccount ( );

66 The Default Constructor
A default constructor uses no parameters A default constructor for the BankAccount class could be declared in this way class BankAccount { public: BankAccount( ); // initializes balance to $ // initializes rate to 0.0% … // The rest of the class definition };

67 Default Constructor Definition
The default constructor for the BankAccount class could be defined as BankAccount::BankAccount( ) { balance = 0; rate = 0.0; } It is a good idea to always include a default constructor even if you do not want to initialize variables

68 Calling the Default Constructor
The default constructor is called during declaration of an object An argument list is not used BankAccount account1; // uses the default BankAccount constructor BankAccount account1( ); // Is not legal Display 10.6 (1) Display 10.6 (2) Display 10.6 (3)

69 Initialization Sections
An initialization section in a function definition provides an alternative way to initialize member variables BankAccount::BankAccount( ): balance(0), interest_rate(0.0); { // No code needed in this example } The values in parenthesis are the initial values for the member variables listed

70 Parameters and Initialization
Member functions with parameters can use initialization sections BankAccount::BankAccount(int dollars, int cents, double rate) : balance (dollars * cents), interest_rate(rate) { if (( dollars < 0) || (cents < 0) || (rate < 0)) { cout << “Illegal values for money or rate\n”; exit(1); } } Notice that the parameters can be arguments in the initialization

71 Member Initializers C++11 supports a feature called member initialization Simply set member variables in the class Ex: class Coordinate { private: int x=1; int y=2; ... }; Creating a Coordinate object will initialize its x variable to 1 and y to 2 (assuming a constructor isn’t called that sets the values to something else)

72 Constructor Delegation
C++11 also supports constructor delegation. This lets you have a constructor invoke another constructor in the initialization section. For example, make the default constructor call a second constructor that sets X to 99 and Y to 99: Coordinate::Coordinate() : Coordinate(99,99) { }

73 Section 10.2 Conclusion Can you
Describe the difference between a class and a structure? Explain why member variables are usually private? Describe the purpose of a constructor? Use an initialization section in a function definition?

74 10.3 Abstract Data Types

75 Abstract Data Types A data type consists of a collection of values together with a set of basic operations defined on the values A data type is an Abstract Data Type (ADT) if programmers using the type do not have access to the details of how the values and operations are implemented

76 Classes To Produce ADTs
To define a class so it is an ADT Separate the specification of how the type is used by a programmer from the details of how the type is implemented Make all member variables private members Basic operations a programmer needs should be public member functions Fully specify how to use each public function Helper functions should be private members

77 ADT Interface The ADT interface tells how to use the ADT in a program
The interface consists of The public member functions The comments that explain how to use the functions The interface should be all that is needed to know how to use the ADT in a program

78 ADT Implementation The ADT implementation tells how the interface is realized in C++ The implementation consists of The private members of the class The definitions of public and private member functions The implementation is needed to run a program The implementation is not needed to write the main part of a program or any non-member functions

79 ADT Benefits Changing an ADT implementation does require changing a program that uses the ADT ADT’s make it easier to divide work among different programmers One or more can write the ADT One or more can write code that uses the ADT Writing and using ADTs breaks the larger programming task into smaller tasks

80 Program Example The BankAccount ADT
In this version of the BankAccount ADT Data is stored as three member variables The dollars part of the account balance The cents part of the account balance The interest rate This version stores the interest rate as a fraction The public portion of the class definition remains unchanged from the version of Display 10.6 Display 10.7 (1) Display 10.7 (3) Display 10.7 (2)

81 Interface Preservation
To preserve the interface of an ADT so that programs using it do not need to be changed Public member declarations cannot be changed Public member definitions can be changed Private member functions can be added, deleted, or changed

82 Information Hiding Information hiding was refered to earlier as writing functions so they can be used like black boxes ADT’s implement information hiding because The interface is all that is needed to use the ADT Implementation details of the ADT are not needed to know how to use the ADT Implementation details of the data values are not needed to know how to use the ADT

83 Section 10.3 Conclusion Can you Describe an ADT?
Describe how to implement an ADT in C++? Define the interface of an ADT? Define the implementation of an ADT?

84 Object Oriented Programming
Review from Chapter 1 Object Oriented Programming

85 Object Oriented Programming
Abbreviated OOP Used for many modern programs Program is viewed as interacting objects Each object contains algorithms to describe its behavior Program design phase involves designing objects and their algorithms

86 OOP Characteristics Encapsulation Information hiding
Objects contain their own data and algorithms Inheritance Writing reusable code Objects can inherit characteristics from other objects Polymorphism A single name can have multiple meanings depending on its context

87 Object-Oriented Programming Terminology
object: software entity that combines data and functions that act on the data in a single unit attributes: the data items of an object, stored in member variables member functions (methods): procedures/ functions that act on the attributes of the class

88 More Object-Oriented Programming Terminology
data hiding: restricting access to certain members of an object. The intent is to allow only member functions to directly access and modify the object’s data encapsulation: the bundling of an object’s data and procedures into a single entity

89 Why Hide Data? Protection – Member functions provide a layer of protection against inadvertent or deliberate data corruption Need-to-know – A programmer can use the data via the provided member functions. As long as the member functions return correct information, the programmer needn’t worry about implementation details.

90 7.2 Object-Oriented Programming
Procedural programming uses variables to store data, and focuses on the processes/ functions that occur in a program. Data and functions are separate and distinct. Object-oriented programming is based on objects that encapsulate the data and the functions that operate on it.

91 Object Example Square object’s data item: side
Member variables (attributes) int side; Member functions void setSide(int s) { side = s; } int getSide() { return side; } Square object’s data item: side Square object’s functions: setSide - set the size of the side of the square, getSide - return the size of the side of the square

92 Introduction to Inheritance
10.4 Introduction to Inheritance

93 Inheritance Inheritance refers to derived classes
Derived classes are obtained from another class by adding features A derived class inherits the member functions and variables from its parent class without having to re-write them Example In Chapter 6 we saw that the class of input-file streams is derived from the class of all input streams by adding member functions such as open and close cin belongs to the class of all input streams, but not the class of input-file streams

94 Inheritance Example Natural hierarchy of bank accounts
Most general: A Bank Account stores a balance A Checking Account “IS A” Bank Account that allows customers to write checks A Savings Account “IS A” Bank Account without checks but higher interest Accounts are more specific as we go down the hierarchy Each box can be a class

95 Inheritance Relationships
The more specific class is a derived or child class The more general class is the base, super, or parent class If class B is derived from class A Class B is a derived class of class A Class B is a child of class A Class A is the parent of class B Class B inherits the member functions and variables of class A

96 Defining Derived Classes
Give the class name as normal, but add a colon and then the name of the base class Objects of type SavingsAccount can access member functions defined in SavingsAccount or BankAccount class SavingsAccount : public BankAccount { } Display 10.9 (1-3)

97 Section 10.4 Conclusion Can you Define object? Define class?
Describe the relationship between parent and child classes? Describe the benefit of inheritance?

98 Chapter End

99 Display (1/2) Back Next

100 Display 10.1 (2/2) Back Next

101 Display 10.2 Back Next

102 Display 10.3 (1/2) Back Next

103 Display 10.3 (2/2) Back Next

104 Display (1/2) Back Next

105 Display 10.4 (2/2) Back Next

106 Display 10.5 (1/4) Back Next

107 Display 10.5 (2/4) Back Next

108 Display 10.5 (3/4) Back Next

109 Display 10.5 (4/4) Back Next

110 Display (1/3) Back Next

111 Display 10.6 (2/3) Back Next

112 Display (3/3) Back Next

113 Display 10.7 (1/3) Back Next

114 Display 10.7 (2/3) Back Next

115 Display 10.7 (3/3) Back Next

116 Display 10.8 Back Next

117 Display 10.9 (1/3) Back Next

118 Display 10.9 (2/3) Back Next

119 Display 10.9 (3/3) Back Next

120

121

122 Introduction to Computers and C++ Programming
Chapter 1 Introduction to Computers and C++ Programming

123 Chapter 7: Introduction to Classes and Objects
Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

124 Topics 7.1 Abstract Data Types 7.2 Object-Oriented Programming
7.3 Introduction to Classes 7.4 Creating and Using Objects 7.5 Defining Member Functions 7.6 Constructors 7.7 Destructors 7.8 Private Member Functions

125 Topics (Continued) 7.9 Passing Objects to Functions 7.10 Object Composition 7.11 Separating Class Specification, Implementation, and Client Code

126 7.1 Abstract Data Types Structures/Classes that are defined by the operations that are performed by/on it. Have no implementation defined “interface contract” that the object provides

127 7.1 Abstract Data Types Programmer-created data types that specify
legal values that can be stored operations that can be done on the values The user of an abstract data type (ADT) does not need to know any implementation details (e.g., how the data is stored or how the operations on it are carried out)

128 Abstraction in Software Development
Abstraction allows a programmer to design a solution to a problem and to use data items without concern for how the data items are implemented This has already been encountered in the book: To use the pow function, you need to know what inputs it expects and what kind of results it produces You do not need to know how it works

129 Abstraction and Data Types
Abstraction: a definition that captures general characteristics without details ex: An abstract triangle is a 3-sided polygon. A specific triangle may be scalene, isosceles, or equilateral Data Type: defines the kind of values that can be stored and the operations that can be performed on it

130 7.6 Constructors A constructor is a member function that is often used to initialize data members of a class Is called automatically when an object of the class is created It must be a public member function It must be named the same as the class It must have no return type See pr7-04.cpp and pr7-05.cpp

131 Constructor – 2 Examples
Inline: class Square { . . . public: Square(int s) { side = s; } }; Declaration outside the class: Square(int); //prototype //in class Square::Square(int s) side = s; }

132 Overloading Constructors
A class can have more than 1 constructor Overloaded constructors in a class must have different parameter lists Square(); Square(int); See pr7-06.cpp

133 The Default Constructor
Constructors can have any number of parameters, including none A default constructor is one that takes no arguments either due to No parameters or All parameters have default values If a class has any programmer-defined constructors, it must have a programmer- defined default constructor

134 Default Constructor Example
class Square { private: int side; public: Square() // default { side = 1; } // constructor // Other member // functions go here }; Has no parameters

135 Another Default Constructor Example
class Square { private: int side; public: Square(int s = 1) // default { side = s; } // constructor // Other member // functions go here }; Has parameter but it has a default value

136 Invoking a Constructor
To create an object using the default constructor, use no argument list and no () Square square1; To create an object using a constructor that has parameters, include an argument list Square square1(8);

137 7.7 Destructors Is a public member function automatically called when an object is destroyed The destructor name is ~className, e.g., ~Square It has no return type It takes no arguments Only 1 destructor is allowed per class (i.e., it cannot be overloaded) See pr7-07.cpp

138 7. 8 Private Member Functions
A private member function can only be called by another member function of the same class It is used for internal processing by the class, not for use outside of the class See pr7-08.cpp

139 7.9 Passing Objects to Functions
A class object can be passed as an argument to a function When passed by value, function makes a local copy of object. Original object in calling environment is unaffected by actions in function When passed by reference, function can use ‘set’ functions to modify the object. See pr7-09.cpp

140 Notes on Passing Objects
Using a value parameter for an object can slow down a program and waste space Using a reference parameter speeds up program, but allows the function to modify data in the parameter

141 Notes on Passing Objects
To save space and time, while protecting parameter data that should not be changed, use a const reference parameter void showData(const Square &s) // header In order to for the showData function to call Square member functions, those functions must use const in their prototype and header: int Square::getSide() const;

142 Returning an Object from a Function
A function can return an object Square initSquare(); // prototype s1 = initSquare(); // call The function must define a object for internal use to use with return statement

143 Returning an Object Example
Square initSquare() { Square s; // local variable int inputSize; cout << "Enter the length of side: "; cin >> inputSize; s.setSide(inputSize); return s; } See pr7-10.cpp

144 7.10 Object Composition Occurs when an object is a member variable of another object. It is often used to design complex objects whose members are simpler objects ex. (from book): Define a rectangle class. Then, define a carpet class and use a rectangle object as a member of a carpet object. See pr7-11.cpp

145 Object Composition, cont.

146 Chapter 7: Introduction to Classes and Objects
Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

147 7.11 Separating Class Specification, Implementation, and Client Code
Separating class declaration, member function definitions, and the program that uses the class into separate files is considered good design

148 Using Separate Files Place class declaration in a header file that serves as the class specification file. Name the file classname.h (for example, Square.h) Place member function definitions in a class implementation file. Name the file classname.cpp (for example, Square.cpp)This file should #include the class specification file. A client program (client code) that uses the class must #include the class specification file and be compiled and linked with the class implementation file. See pr7-12.cpp, Rectangle.cpp, and Rectangle.h

149 Include Guards Used to prevent a header file from being included twice
Format: #ifndef symbol_name #define symbol_name (normal contents of header file) #endif symbol_name is usually the name of the header file, in all capital letters: #ifndef SQUARE_H #define SQUARE_H . . .

150 What Should Be Done Inside vs. Outside the Class
Class should be designed to provide functions to store and retrieve data In general, input and output (I/O) should be done by functions that use class objects, rather than by class member functions See Rectangle.h, Rectangle.cpp, and pr7-12.cpp

151 Chapter 7: Introduction to Classes and Objects
Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda

152 7.14 Introduction to Object-Oriented Analysis and Design
Object-Oriented Analysis: that phase of program development when the program functionality is determined from the requirements It includes identification of objects and classes definition of each class's attributes identification of each class's behaviors definition of the relationship between classes

153 Identify Objects and Classes
Consider the major data elements and the operations on these elements Candidates include user-interface components (menus, text boxes, etc.) I/O devices physical objects historical data (employee records, transaction logs, etc.) the roles of human participants

154 Define Class Attributes
Attributes are the data elements of an object of the class They are necessary for the object to work in its role in the program

155 Define Class Behaviors
For each class, Identify what an object of a class should do in the program The behaviors determine some of the member functions of the class

156 Relationships Between Classes
Possible relationships Access ("uses-a") Ownership/Composition ("has-a") Inheritance ("is-a")

157 Finding the Classes Technique:
Write a description of the problem domain (objects, events, etc. related to the problem) List the nouns, noun phrases, and pronouns. These are all candidate objects Refine the list to include only those objects that are relevant to the problem

158 Determine Class Responsibilities
What is the class responsible to know? What is the class responsible to do? Use these to define some of the member functions

159 Object Reuse A well-defined class can be used to create objects in multiple programs By re-using an object definition, program development time is shortened One goal of object-oriented programming is to support object reuse

160 Chapter 7: Introduction to Classes and Objects
Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda


Download ppt "Chapter 10 Defining Classes. Chapter 10 Defining Classes."

Similar presentations


Ads by Google