Download presentation
Presentation is loading. Please wait.
1
Recitation Course 0610 Speaker: Liu Yu-Jiun
2
Chap 12 Inheritance
3
Introduction Create new class from existing class
Absorb existing class’s data and behaviors Enhance with new capabilities Derived class inherits from base class Derived class More specialized group of objects Behaviors inherited from base class Can customize Additional behaviors Relationship Composition: has a relationship Inheritance: is a relationship
4
is-a Base class Derived class Direct base class Indirect base class
Base and derived class is-a Base class Derived class Direct base class Indirect base class
5
12.2 base class and derived class
public inheritance: Specify with: class derived_class_name : public base_class_name Example: class TwoDimensionalShape : public Shape Base class private members Still inherited, but not accessible directly Base class public and protected members Inherited with original member access friend function Not inherited
6
12.3 protected Members protected access Derived-class members
Intermediate level of protection between public and private protected members are accessible to Base class members Base class friends Derived class members Derived class friends Derived-class members Refer to public and protected members of base class Simply use member names Redefined base class members can be accessed by using base-class name and binary scope resolution operator (::) 衍生類別如果想用基本類別中的public和protected成員,只要直接使用就好。 如果衍生類別重新定義了基本類別的成員(衍生類別有成員和基本類別成員的名稱相同,但是功能不同),只要加上基本類別的名稱和::
7
12.4 Relationship between Base Classes and Derived Classes
Five examples: Class CommissionEmployee Class BasePlusCommissionEmployee (v1) Without inheritance Class BasePlusCommissionEmployee (v2) Inherit from class CommissionEmployee Use private member in base class Class BasePlusCommissionEmployee (v3) Let private members be protected members in base class Class BasePlusCommissionEmployee (v4) Use public member function in base class to access private members in base class
8
12.4.1 class CommissionEmployee
9
5 pairs of set and get functions for accessing each data member
// Fig. 12.4: CommissionEmployee.h #ifndef COMMISSION_H #define COMMISSION_H #include <string> using namespace std; class CommissionEmployee{ public: CommissionEmployee(const string &, const string &, const string &, double = 0.0, double = 0.0); void setFirstName(const string &); string getFirstName() const; void setLastName(const string &); void setSocialSecurityNumber(const string &); void setGrossSales(double); double getFirstName() const; void setCommissionRate(double); double earnings() const; void print() const; private: string firstName; string lastName; string socialSecurityNumber; double grossSales; double commissionRate; }; #endif 5 pairs of set and get functions for accessing each data member
10
10 Outline Commission Employee.cpp (1 of 4) Initialize data members 10
11
Outline (2 of 4) Function setGrossSales validates gross sales amount
11 Outline Commission Employee.cpp (2 of 4) Function setGrossSales validates gross sales amount 11
12
Outline Function setCommissionRate validates commission rate (3 of 4)
12 Outline Function setCommissionRate validates commission rate Commission Employee.cpp (3 of 4) 12
13
Outline Function earnings calculates earnings (4 of 4)
13 Outline Function earnings calculates earnings Commission Employee.cpp (4 of 4) Function print displays CommissionEmployee object 13
14
Outline (1 of 2) Instantiate CommissionEmployee object
14 Outline fig12_06.cpp (1 of 2) Instantiate CommissionEmployee object Use CommissionEmployee’s get functions to retrieve the object’s instance variable values 14
15
15 Outline Use CommissionEmployee’s set functions to change the object’s instance variable values fig12_06.cpp (2 of 2) Call object’s print function to display employee information Call object’s earnings function to calculate earnings 15
16
Class BasePlusCommissionEmployee
16 Creating a BasePlusCommissionEmployee Class Without Using Inheritance Class BasePlusCommissionEmployee Much of the code is similar to CommissionEmployee private data members public methods constructor Additions private data member baseSalary Methods setBaseSalary and getBaseSalary 16
17
17 Outline BasePlus Commission Employee.h (1 of 2) Constructor takes one more argument, which specifies the base salary 與類別CommissionEmployee重複 17
18
Outline Define get and set functions for data member baseSalary
18 Define get and set functions for data member baseSalary Outline BasePlus Commission Employee.h (2 of 2) Add data member baseSalary 18
19
19 Outline BasePlus Commission Employee.cpp (1 of 4) Constructor takes one more argument, which specifies the base salary Use function setBaseSalary to validate data 19
20
20 Outline BasePlus Commission Employee.cpp (2 of 4) 20
21
21 Outline BasePlus Commission Employee.cpp (3 of 4) 21
22
22 Outline Function setBaseSalary validates data and sets instance variable baseSalary BasePlus Commission Employee.cpp (4 of 4) Function getBaseSalary returns the value of instance variable baseSalary Update function earnings to calculate the earnings of a base-salaried commission employee Update function print to display base salary 22
23
Outline (1 of 3) Instantiate BasePlusCommissionEmployee object 23
fig12_09.cpp (1 of 3) Instantiate BasePlusCommissionEmployee object 23
24
24 Outline Use BasePlusCommissionEmployee’s get functions to retrieve the object’s instance variable values fig12_09.cpp (2 of 3) Use BasePlusCommissionEmployee’s setBaseSalary function to set base salary Call object’s print function to display employee information Call object’s earnings function to calculate employee’s earnings 24
25
25 Outline fig12_09.cpp (3 of 3) 25
26
12.4.3 Creating a CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy
Class BasePlusCommissionEmployee Derived from class CommissionEmployee Is a CommissionEmployee Inherits all public members Constructor is not inherited Use base-class initializer syntax to initialize base-class data member Has data member baseSalary 26
27
Include the base-class header file in the derived-class header file:
Know that base class exist. Know size of inherited data members.(併入衍生類別物件的總記憶體需求量) Ensure that inherited class members are used properly. Class BasePlusCommissionEmployee derives publicly from class CommissionEmployee 27
28
在成員初始值列表初始化成員物件並明確的呼叫基本類別建構子,可以避免重複初始化的問題。
Initialize base class data member by calling the base-class constructor using base-class initializer syntax. 在成員初始值列表初始化成員物件並明確的呼叫基本類別建構子,可以避免重複初始化的問題。 28
29
Compiler generates errors because base class’s data member commissionRate and grossSales are private
Compiler generates errors because the base class’s data members firstName, lastName, socialSecurityNumber, grossSales and commissionRate are private 29
30
30
31
12.4.4 CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy Using protected Data
Use protected data Enable class BasePlusCommissionEmployee to directly access base class data members Base class’s protected members are inherited by all derived classes of that base class 31
32
CommissionEmployee.h相同
// Fig. 12.4: CommissionEmployee.h #ifndef COMMISSION_H #define COMMISSION_H #include <string> using namespace std; class CommissionEmployee{ public: CommissionEmployee(const string &, const string &, const string &, double = 0.0, double = 0.0); void setFirstName(const string &); string getFirstName() const; void setLastName(const string &); void setSocialSecurityNumber(const string &); void setGrossSales(double); double getFirstName() const; void setCommissionRate(double); double earnings() const; void print() const; private: string firstName; string lastName; string socialSecurityNumber; double grossSales; double commissionRate; }; #endif protected: 幾乎與12.4.1的 CommissionEmployee.h相同
33
CommissionEmployee.cpp完全相同
33 Outline Commission Employee.cpp (1 of 3) 與12.4.1的 CommissionEmployee.cpp完全相同 33
34
CommissionEmployee.cpp完全相同
34 Outline Commission Employee.cpp (2 of 3) 與12.4.1的 CommissionEmployee.cpp完全相同 34
35
CommissionEmployee.cpp完全相同
35 Outline Commission Employee.cpp (3 of 3) 與12.4.1的 CommissionEmployee.cpp完全相同 35
36
BasePlusCommissionEmployee.h完全相同
36 Outline BasePlus Commission Employee.h (1 of 1) BasePlusCommissionEmployee still inherits publicly from CommissionEmployee 與12.4.3的 BasePlusCommissionEmployee.h完全相同 36
37
BasePlusCommissionEmployee.cpp完全相同
37 Outline BasePlus Commission Employee.cpp (1 of 2) Call base-class constructor using base-class initializer syntax 與12.4.3的 BasePlusCommissionEmployee.cpp完全相同 37
38
BasePlusCommissionEmployee.cpp完全相同
38 Outline BasePlus Commission Employee.cpp (2 of 2) Directly access base class’s protected data 與12.4.3的 BasePlusCommissionEmployee.cpp完全相同 38
39
39 Outline Fig12_16.cpp (1 of 2) 39
40
40 Outline Fig12_16.cpp (2 of 2) 與12.4.2的程式功能相同, 但是程式碼變短,也比較容易維護 40
41
41 CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy Using protected Data (Cont.) Advantages Derived class can modify values directly Avoid set/get method call overhead Slight increase in performance Disadvantages No validity checking Derived class can assign illegal value Implementation dependent Derived class functions more likely dependent on base class implementation Base class implementation changes may result in derived class modifications Fragile (brittle) software 41
42
12.4.5 CommissionEmployee-BasePlusCommissionEmployee Inheritance Hierarchy Using private Data
Reexamine hierarchy Use the best software engineering practice Declare data members as private Provide public get and set functions Use get method to obtain values of data members 42
43
CommissionEmployee.h相同
// Fig. 12.4: CommissionEmployee.h #ifndef COMMISSION_H #define COMMISSION_H #include <string> using namespace std; class CommissionEmployee{ public: CommissionEmployee(const string &, const string &, const string &, double = 0.0, double = 0.0); void setFirstName(const string &); string getFirstName() const; void setLastName(const string &); void setSocialSecurityNumber(const string &); void setGrossSales(double); double getFirstName() const; void setCommissionRate(double); double earnings() const; void print() const; private: string firstName; string lastName; string socialSecurityNumber; double grossSales; double commissionRate; }; #endif 與12.4.1的 CommissionEmployee.h相同
44
44 Outline Commission Employee.cpp (1 of 3) Use member initializers to set the values of members firstName, lastname and socialSecurityNumber 44
45
45 Outline Commission Employee.cpp (2 of 3) 45
46
46 Outline Commission Employee.cpp (3 of 3) Use get functions to obtain the values of data members 46
47
12.5 Constructors and Destructors in Derived Classes
Instantiating derived-class object Chain of constructor calls Derived-class constructor invokes base class constructor Implicitly or explicitly Base of inheritance hierarchy Last constructor called in chain First constructor body to finish executing Example: CommissionEmployee/BasePlusCommissionEmployee hierarchy CommissionEmployee constructor called last CommissionEmployee constructor body finishes execution first Initializing data members Each base-class constructor initializes its data members that are inherited by derived class 47
48
12.5 Constructors and Destructors in 12.4.3~4
類別BasePlusCommissionEmployee constructor的主體(使用域、scope) 48
49
12.5 Constructors and Destructors in Derived Classes (Cont.)
Destroying derived-class object Chain of destructor calls Reverse order of constructor chain Destructor of derived-class called first Destructor of next base class up hierarchy next Continue up hierarchy until final base reached After final base-class destructor, object removed from memory Base-class constructors, destructors, assignment operators Not inherited by derived classes 49
50
12.6 public, protected and private Inheritance
50 12.6 public, protected and private Inheritance public inheritance Base class public members derived class public members Base class protected members derived class protected members Base class private members are not accessible protected inheritance (not is-a relationship) Base class public and protected members derived class protected members private inheritance (not is-a relationship) Base class public and protected members derived class private members 50
51
51
52
Exercise 12.9 Package + 12 pairs set and get functions
senderName:string recipientName:string senderAddress:string -recipientAddress:string senderCity:string recipientCity:string senderState:string recipientState:string senderZip:int recipientZip:int weight:double costPerOunce:double + 12 pairs set and get functions + calculateCost() : double TwoDayPackage OvernightPackage - flatFee : double - overnightFeePerOunce : double + setFlatFee(double) + getFlatFee(): double + calculateCost() : double + setOvernightFeePerOunce(double) + getOvernightFeePerOunce(): double + calculateCost(): double
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.