




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、Chapter 15InheritanceOverview15.1 Inheritance Basics 15.2 Inheritance Details 15.3 PolymorphismSlide 15- 315.1InheritanceInheritance Basics Inheritance is the process by which a new class,called a derived class, is created from anotherclass, called the base classA derived class automatically has all
2、 the member variables and functions of the base classA derived class can have additional member variables and/or member functionsThe derived class is a child of the base or parent classSlide 15- 5Example Inheritance Hierarchy for Home Automation DevicesSlide 15- 6Devicestring modelstring serialNumbe
3、rstring status()DoorDevicestring status()void openClose()ThermostatDevicestring status()void setTemp(int t)IS-AIS-ADISPLAY 15.1 base orparent classderived or child classderived or child classAn object of type DoorDevice or ThermostatDevice includes functions and variables defined in Device, such as
4、model and serialNumber.The status() function can be overridden. If a DoorDevice object is treated like a Device object, then calling status()will invoke DoorDevices status() function, not Devices status()function. This is necessary when the Device class doesnt know what to return as a status and onl
5、y the derived classes can return the information.Employee ClassesTo design a record-keeping program with records for salaried and hourly employeesSalaried and hourly employees belong to a class of people who share the property employeeA subset of employees are those with a fixed wageAnother subset o
6、f employees earn hourly wagesAll employees have a name and SSNFunctions to manipulate name and SSN are the samefor hourly and salaried employeesSlide 15- 7A Base ClassWe will define a class called Employee for all employeesThe Employee class will be used to define classes for hourly and salaried emp
7、loyeesA definition of the employee class is found in Slide 15- 8Display 15.2Display 15.3Function printCheckFunction printCheck will have different definitions to print different checks for each type of employeeAn Employee object lacks sufficient information to print a checkEach derived class will ha
8、ve sufficient information to print a checkSlide 15- 9Class HourlyEmployeeHourlyEmployee is derived from Class EmployeeHourlyEmployee inherits all member functions and member variables of Employee The class definition begins class HourlyEmployee : public Employee:public Employee shows that HourlyEmpl
9、oyee is derived from class EmployeeHourlyEmployee declares additional member variables wageRate and hours Slide 15- 10Display 15.4Inherited MembersA derived class inherits all the members of the parent classThe derived class does not re-declare or re-define members inherited from the parent, exceptT
10、he derived class re-declares and re-defines member functions of the parent class that will have a different definition in the derived classThe derived class can add member variables and functionsSlide 15- 11Implementing a Derived ClassAny member functions added in the derived class are defined in th
11、e implementation file forthe derived classDefinitions are not given for inherited functions that are not to be changedThe HourlyEmployee class is defined in Slide 15- 12Display 15.6Class SalariedEmployeeThe class SalariedEmployee is also derived fromEmployeeFunction printCheck is redefined to have a
12、 meaning specific to salaried employees SalariedEmployee adds a member variable salaryThe interface for SalariedEmployee is found in contains the implementationSlide 15- 13Display 15.5Display 15.7 (1-2)Parent and Child ClassesRecall that a child class automatically has all the members of the parent
13、classThe parent class is an ancestor of the child classThe child class is a descendent of the parentclassThe parent class (Employee) contains all the code common to the child classesYou do not have to re-write the code for each childSlide 15- 14Derived Class TypesAn hourly employee is an employeeIn
14、C+, an object of type HourlyEmployee can be used where an object of type Employee can be usedAn object of a class type can be used wherever any of its ancestors can be usedAn ancestor cannot be used wherever one of its descendents can be used Slide 15- 15Derived Class ConstructorsA base class constr
15、uctor is not inherited in a derived classThe base class constructor can be invoked by the constructor of the derived classThe constructor of a derived class begins by invokingthe constructor of the base class in the initializationsection: HourlyEmployee:HourlyEmployee : Employee( ), wageRate( 0), ho
16、urs( ) /no code needed Slide 15- 16Any Employee constructor could be invokedDefault InitializationIf a derived class constructor does not invoke abase class constructor explicity, the base classdefault constructor will be usedIf class B is derived from class A and class Cis derived from class BWhen
17、a object of class C is created The base class As constructor is the first invokedClass Bs constructor is invoked nextCs constructor completes executionSlide 15- 17Private is PrivateA member variable (or function) that is privatein the parent class is not accessible to the child classThe parent class
18、 member functions must be used to access the private members of the parentThis code would be illegal: void HourlyEmployee:printCheck( ) netPay = hours * wageRate;netPay is a private member of Employee!Slide 15- 18The protected Qualifierprotected members of a class appear to be private outside the cl
19、ass, but are accessible by derived classesIf member variables name, netPay, and ssn are listed as protected (not private) in the Employee class, this code, illegal on the previous slide, becomes legal: HourlyEmployee:printCheck( ) netPay = hours * wageRate;Slide 15- 19Programming StyleUsing protecte
20、d members of a class is a convenience to facilitate writing the code of derived classes.Protected members are not necessaryDerived classes can use the public methods of their ancestor classes to access private membersMany programming authorities consider it bad style to use protected member variable
21、sSlide 15- 20Redefinition of Member FunctionsWhen defining a derived class, only list the the inherited functions that you wish to changefor the derived classThe function is declared in the class definitionHourlyEmployee and SalariedEmployee each have their own definitions of printCheck demonstrates
22、 the use of the derived classes defined in earlier displays.Slide 15- 21Display 15.8 (1-2)Redefining or OverloadingA function redefined in a derived class has the same number and type of parametersThe derived class has only one function with the same name as the base classAn overloaded function has
23、a different number and/or type of parameters than the base classThe derived class has two functions with the same name as the base classOne is defined in the base class, one in the derived classSlide 15- 22Function SignaturesA function signature is the functions name with the sequence of types in th
24、e parameterlist, not including any const or &An overloaded function has multiple signaturesSome compilers allow overloading based on including const or not including constSlide 15- 23Access to a Redefined Base FunctionWhen a base class function is redefined in a derived class, the base class functio
25、n can still be usedTo specify that you want to use the base class version of the redefined function: HourlyEmployee sallyH; sallyH.Employee:printCheck( );Slide 15- 24Section 15.1 ConclusionCan youExplain why the declaration for getName is not part of the definition of SalariedEmployee?Give a definit
26、ion for a class TitledEmployee derived from class SalariedEmployee with one additional string called title? Add two member functions getTitle and setTitle. It should redefine setName.Slide 15- 2515.2Inheritance DetailsInheritance DetailsSome special functions are, for all practicalpurposes, not inhe
27、rited by a derived classSome of the special functions that are not effectively inherited by a derived class includeDestructorsCopy constructorsThe assignment operatorSlide 15- 27Copy Constructors and Derived ClassesIf a copy constructor is not defined in a derivedclass, C+ will generate a default co
28、py constructorThis copy constructor copies only the contents of member variables and will not work with pointers and dynamic variablesThe base class copy constructor will not be usedSlide 15- 28Operator = and Derived ClassesIf a base class has a defined assignment operator = and the derived class do
29、es not:C+ will use a default operator that will have nothing to do with the base class assignment operatorSlide 15- 29Destructors and Derived ClassesA destructor is not inherited by a derived classThe derived class should define its own destructorSlide 15- 30The Assignment OperatorIn implementing an
30、 overloaded assignment operator in a derived class:It is normal to use the assignment operator from the base class in the definition of the derived classs assignment operatorRecall that the assignment operator is written as a member function of a classSlide 15- 31The Operator = ImplementationThis co
31、de segment shows how to begin the implementation of the = operator for a derived class: Derived& Derived:operator= (const Derived& rhs) Base:operator=(rhs)This line handles the assignment of the inherited member variables by calling the base class assignment operatorThe remaining code would assign t
32、he member variables introduced in the derived classSlide 15- 32The Copy ConstructorImplementation of the derived class copy constructor is much like that of the assignment operator:Derived:Derived(const Derived& object) :Base(object), Invoking the base class copy constructor sets up the inherited me
33、mber variablesSince object is of type Derived it is also of type BaseSlide 15- 33Destructors in Derived ClassesIf the base class has a working destructor, defining the destructor for the defined class is relatively easyWhen the destructor for a derived class is called, the destructor for the base cl
34、ass is automatically calledThe derived class destructor need only use delete on dynamic variables added in the derived class, and data they may point toSlide 15- 34Destruction SequenceIf class B is derived from class A and class Cis derived from class BWhen the destructor of an object of class C goe
35、s out of scopeThe destructor of class C is calledThen the destructor of class BThen the destructor of class ANotice that destructors are called in the reverse order of constructor callsSlide 15- 35Section 15.2 ConclusionCan youList some special functions that are not inherited by a derived class?Wri
36、te code to invoke the base class copy constructor in defining the derived classs copy constructor?Slide 15- 3615.3PolymorphismPolymorphismPolymorphism refers to the ability to associatemultiple meanings with one function name using a mechanism called late bindingPolymorphism is a key component of th
37、e philosophy of object oriented programmingSlide 15- 38A Late Binding ExampleImagine a graphics program with several types of figuresEach figure may be an object of a different class, such as a circle, oval, rectangle, etc.Each is a descendant of a class FigureEach has a function draw( ) implemented
38、 with code specific to each shapeClass Figure has functions common to all figuresSlide 15- 39A ProblemSuppose that class Figure has a function centerFunction center moves a figure to the center of the screen by erasing the figure and redrawing it in the center of the screenFunction center is inherit
39、ed by each of the derived classesFunction center uses each derived objects draw function to draw the figureThe Figure class does not know about its derived classes, so it cannot know how to draw each figureSlide 15- 40Virtual FunctionsBecause the Figure class includes a method to draw figures, but t
40、he Figure class cannot knowhow to draw the figures, virtual functions are usedMaking a function virtual tells the compiler thatyou dont know how the function is implementedand to wait until the function is used in aprogram, then get the implementation from the object. This is called late bindingSlid
41、e 15- 41Virtual Functions in C+As another example, lets design a record-keeping program for an auto parts store We want a versatile program, but we do not know all the possible types of sales we might have to account forLater we may add mail-order and discount salesFunctions to compute bills will ha
42、ve to be added later when we know what type of sales to addTo accommodate the future possibilities, we will make the bill function a virtual functionSlide 15- 42The Sale ClassAll sales will be derived from the base class SaleThe bill function of the Sale class is virtualThe member function savings a
43、nd operator each use billThe Sale class interface and implementationare shown in Slide 15- 43Display 15.9Display 15.10Virtual Function billBecause function bill is virtual in class Sale, function savings and operator , defined only in the base class, can in turn use a version of billfound in a deriv
44、ed classWhen a DiscountSale object calls its savings function, defined only in the base class, function savings calls function billBecause bill is a virtual function in class Sale, C+ uses the version of bill defined in the object that called savingsSlide 15- 44DiscountSale:billClass DiscountSale ha
45、s its own version of virtual function billEven though class Sale is already compiled, Sale:savings( ) and Sale:operator can still use function bill from the DiscountSale classThe keyword virtual tells C+ to wait until bill is used in a program to get the implementation of bill from the calling objec
46、tDiscountSale is defined and used in Slide 15- 45Display 15.11Display 15.12Virtual DetailsTo define a function differently in a derived classand to make it virtualAdd keyword virtual to the function declaration in the base classvirtual is not needed for the function declaration in the derived class,
47、 but is often includedvirtual is not added to the function definitionVirtual functions require considerable overhead so excessive use reduces program efficiencySlide 15- 46OverridingVirtual functions whose definitions are changedin a derived class are said to be overriddenNon-virtual functions whose
48、 definitions are changed in a derived class are redefinedSlide 15- 47Type CheckingC+ carefully checks for type mismatches in the use of values and variablesThis is referred to as strong type checkingGenerally the type of a value assigned to a variable must match the type of the variableRecall that s
49、ome automatic type casting occursStrong type checking interferes with the concepts of inheritance Slide 15- 48Type Checking and InheritanceConsider class Pet public: virtual void print(); string name; and class Dog :public Pet public: virtual void print(); string breed; Slide 15- 49A Sliced Dog is a
50、 PetC+ allows the following assignments: = Tiny; vdog.breed = Great Dane; vpet = vdog;However, vpet will loose the breed member of vdog since an object of class Pet has no breedmemberThis code would be illegal: cout print( ); is legal and produces: name: Tiny breed: Great DaneSlide 15- 53v
51、oid Dog:print( ) cout name: name endl; cout breed: breed name = Tiny;pdog-breed = Great Dane;ppet = pdog;Display 15.13 (1-2)Use Virtual FunctionsThe previous example: ppet-print( ); worked because print was declared as a virtualfunctionThis code would still produce an error: cout name: name breed: b
52、reed;Slide 15- 54Why?ppet-breed is still illegal because ppet is a pointer to a Pet object that has no breed memberFunction print( ) was declared virtual by classPet When the computer sees ppet-print( ), it checks the virtual table for classes Pet and Dog and finds that ppet points to an object of t
53、ype DogBecause ppet points to a Dog object, code for Dog:print( )is used Slide 15- 55Remember Two RulesTo help make sense of object oriented programming with dynamic variables, remember these rules If the domain type of the pointer p_ancestor is a base class for the for the domain type of pointer p_descendant, the following assignment of pointers is allow
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- Unit 5 Topic 2 Section C 教學(xué)設(shè)計(jì)-2024-2025學(xué)年仁愛科普版八年級英語下冊
- 二年級下冊數(shù)學(xué)教案-6.1菜園衛(wèi)士-連續(xù)進(jìn)位、退位的三位數(shù)加減三位數(shù) 青島版
- 六年級下冊數(shù)學(xué)教案-四 比例 面積的變化|蘇教版
- 一年級上冊數(shù)學(xué)教案- 老鷹捉小雞 青島版
- 中建三局房屋建筑實(shí)測實(shí)量培訓(xùn)
- (常考易錯題)2022-2023學(xué)年三年級上冊期末高頻考點(diǎn)數(shù)學(xué)試卷(蘇教版)
- 2024年科創(chuàng)大數(shù)據(jù)項(xiàng)目投資申請報(bào)告代可行性研究報(bào)告
- 2025年甘孜職業(yè)學(xué)院單招職業(yè)技能測試題庫及答案一套
- 2025年黑龍江冰雪體育職業(yè)學(xué)院單招職業(yè)技能測試題庫必考題
- 2024年人工種植牙項(xiàng)目資金需求報(bào)告代可行性研究報(bào)告
- 出租共享菜園合同范例
- 八年級班主任學(xué)生心理健康計(jì)劃
- 整體施工勞務(wù)服務(wù)方案
- 傳統(tǒng)節(jié)日端午節(jié)模板37
- 2024 貴州公務(wù)員考試行測真題(省直)
- 2025年泰山職業(yè)技術(shù)學(xué)院高職單招職業(yè)適應(yīng)性測試近5年常考版參考題庫含答案解析
- 2025春季開學(xué)第一次全體教師會上校長講話稿
- 2025年三方買賣協(xié)議標(biāo)準(zhǔn)版本(2篇)
- 2025年南京旅游職業(yè)學(xué)院高職單招職業(yè)適應(yīng)性測試近5年??及鎱⒖碱}庫含答案解析
- 【歷史】唐朝建立與“貞觀之治”課件-2024~2025學(xué)年統(tǒng)編版七年級歷史下冊
- 《小腦梗死護(hù)理查房》課件
評論
0/150
提交評論