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 Overview 10.1 Structures ---- Object Oriented Programming 10.2 Classes 10.3 Abstract Data Types 10.4 Introduction to Inheritance

4 Objects are used to model real-world things.
You can think of an object as a rather complex variable that contains multiple chunks of data

5 Real world objects have attributes
Let’s consider an object that represents a time. Real world objects have attributes An object’s attributes describe its “state of being” seconds minutes am/pm hours

6 We hide the data from anyone outside
of the object by making it “private” Joe WageEarner 12356 $12.50 40 A Time object

7 The attributes of an object are stored inside the object as
data members. The hour value is stored as an integer 3 The minute value is stored as an integer 35 pm am or pm is stored as a string An “Time” object

8 An object also has behaviors
behaviors define how you interact with the object What can you do with a time? set the hours Get the hours

9 getHour ( ) setHour( ) Behaviors are expressed as methods that
give us controlled access to the data. These are “public” so that we can see them. Joe WageEarner 12356 getHour ( ) setHour( ) $12.50 40 An “Time” object

10 Then we write statements that send messages to the objects
Joe WageEarner joe.getHours( ); 12356 getHour ( ) setHour ( ) $12.50 40 An “Time” object named joe

11 An Object’s Attributes and Behaviors Should Work Together
this is called cohesion

12 Encapsulation Encapsulation is
Combining a number of items, such as variables and functions, into a single package such as an object of a class Encapsulation in C++ In normal terms Encapsulation is defined as wrapping up of data and information under a single unit. In Object Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulates them. Consider a real life example of encapsulation, in a company there are different sections like the accounts section, finance section, sales section etc. The finance section handles all the financial transactions and keep records of all the data related to finance. Similarly the sales section handles all the sales related activities and keep records of all the sales. Now there may arise a situation when for some reason an official from finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of sales section and the employees that can manipulate them are wrapped under a single name “sales section”. Encapsulation also lead to data abstraction or hiding. As using encapsulation also hides the data. In the above example the data of any of the section like sales, finance or accounts is hidden from any other section.

13 Encapsulation Time object getHour( ) member methods are calling method
declared as public calling method we should not allow code outside of the object to reach in and change the data directly. Instead, we call methods in the object to do it for us. hour minute member data is declared as private The terms public and private are called access modifiers

14 Introduction to Classes
A class is said to be an abstraction of the real world object that we are modeling. Classes are sometimes called Abstract Data Types. Class: a programmer-defined data type used to define objects It is a pattern for creating objects ex: string fName, lName; creates two objects of the string class

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

16 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

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

18 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

19 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

20 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

21 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; }

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

23 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

24 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

25 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

26 10.2 Classes

27 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

28 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

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

30 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; }

31 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; }

32 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

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

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

35 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

36 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

37 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

38 “Setter”Methods void Time::setHour(int hr) { hour = hr; }
they are usually named “set” plus the name of the instance variable they will store the value in. void Time::setHour(int hr) { hour = hr; } setters never return anything setters always take a parameter

39 “Getter”Methods int Time::getHour( ) const { return hour; }
getters take no parameters getters always return something int Time::getHour( ) const { return hour; } The const keyword is required to tell the compiler that the function does not alter the object. they are usually named “get” plus the name of the instance variable they will return the value of.

40 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

41 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; }

42 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

43 A New DayOfYear Display 10.4 (1) Display 10.4 (2)
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)

44 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

45 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 … };

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

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

48 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( );

49 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; }

50 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

51 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 };

52 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

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

54 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

55 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 ( );

56 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 };

57 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

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

59 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

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

61 Class Memberwise Assignment
Can use = to assign one object to another, or to initialize an object with an object’s data Examples (assuming class V): V v1, v2; … // statements that assign … // values to members of v1 v2 = v1; // assignment V v3 = v2; // initialization See pr11-05.cpp

62 Copy Constructors Special constructor used when a newly created object is initialized to the data of another object of same class Default copy constructor copies field-to-field, using memberwise assignment The default copy constructor works fine in most cases See pr11-06.cpp

63 Programmer-Defined Copy Constructors
A copy constructor is one that takes a reference parameter to another object of the same class The copy constructor uses the data in the object passed as parameter to initialize the object being created Reference parameter should be const to avoid potential for data corruption

64 Copy Constructor – When Is It Used?
A copy constructor is called when An object is initialized from an object of the same class An object is passed by value to a function An object is returned using a return statement from a function

65 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

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

67 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) { }

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

69 10.3 Abstract Data Types

70 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

71 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

72 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

73 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

74 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

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

76 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

77 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

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

79 Object Oriented Programming
Review from Chapter 1 Object Oriented Programming

80 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

81 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

82 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

83 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

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

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

86 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

87 10.3 Abstract Data Types

88 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

89 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

90 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

91 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

92 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

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

94 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

95 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

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

97 Introduction to Inheritance
10.4 Introduction to Inheritance

98 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

99 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

100 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

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

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

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

104 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

105 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

106 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

107 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

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

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

110 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

111 7.3 Introduction to Classes
Class: a programmer-defined data type used to define objects It is a pattern for creating objects ex: string fName, lName; creates two objects of the string class

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

113 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

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

115 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

116 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

117 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

118 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

119 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; }

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

121 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

122 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

123 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

124 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

125 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; }

126 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

127 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

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

129 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

130 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);

131 Destructors (i.e., it cannot be overloaded)
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

132 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

133 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

134 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

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

136 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

137 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

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

139 Object Composition, cont.

140 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

141 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

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

143 Chapter End

144 Display (1/2) Back Next

145 Display 10.1 (2/2) Back Next

146 Display 10.2 Back Next

147 Display 10.3 (1/2) Back Next

148 Display 10.3 (2/2) Back Next

149 Display (1/2) Back Next

150 Display 10.4 (2/2) Back Next

151 Display 10.5 (1/4) Back Next

152 Display 10.5 (2/4) Back Next

153 Display 10.5 (3/4) Back Next

154 Display 10.5 (4/4) Back Next

155 Display (1/3) Back Next

156 Display 10.6 (2/3) Back Next

157 Display (3/3) Back Next

158 Display 10.7 (1/3) Back Next

159 Display 10.7 (2/3) Back Next

160 Display 10.7 (3/3) Back Next

161 Display 10.8 Back Next

162 Display 10.9 (1/3) Back Next

163 Display 10.9 (2/3) Back Next

164 Display 10.9 (3/3) Back Next

165

166

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

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

169 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

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

171 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

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

173 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

174 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

175 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

176 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; }

177 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

178 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

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

180 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

181 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);

182 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

183 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

184 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

185 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

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

187 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

188 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

189 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

190 Object Composition, cont.

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

192 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

193 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

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

195 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

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

197 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

198 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

199 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

200 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

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

202 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

203 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

204 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

205 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