Danh mục

Lecture note Data visualization - Chapter 14

Số trang: 26      Loại file: pptx      Dung lượng: 93.64 KB      Lượt xem: 4      Lượt tải: 0    
Xem trước 3 trang đầu tiên của tài liệu này:

Thông tin tài liệu:

This chapter presents the following content: Introduction to inheritance, inheritance in C++, IS-A relationship, polymorphism in inheritance, classes in inheritance, visibility rules, constructor and base class, adding members.
Nội dung trích xuất từ tài liệu:
Lecture note Data visualization - Chapter 14Lecture14RecapIntroductiontoInheritanceInheritanceinC++ISARelationshipPolymorphisminInheritanceClassesinInheritanceVisibilityRulesConstructorandBaseClassAddingMembersOverridingaMethodMethodscanbeoverridefromthebaseclassinthe derivedclassbysimplyprovidingaderivedclassmethod withthesamesignatureAderivedclassmethodmusthavethesameor compatiblereturntypeSometimesitisrequiredtoinvokethederivedclass methodtothebaseclassmethodtoaugmentabaseclass methodratherthandoingsomethingentirelydifferent. ThisisknownaspartialoverridingThescopeoperatorcanbeusedtocallabaseclass methodExampleclassWorkaholic:publicWorker{public:voiddowork(){Worker::doWork();//WorklikeaWorkerdrinkCoffee();//TakeabreakWorker::doWork();//WorklikeaWorkersomemoreStaticandDynamicBindingExampleCode 1Workerw; 2Workaholicwh; 3... 4w.doWork();wh.doWork();Theabovecodeillustratesthefactthatwecandeclare WorkerandWorkaholicobjectsinthesamescope becausethecompilercandeducewhichdoworkmethodto applywisaWorkerandwhisaWorkaholic,sotheExample1Worker*wptr;2cin>>x;3if(x!=0)4wptr=newWorkaholic();5else6wptr=newWorker();78……ExplanationofExampleIfxiszero,wecreateaWorkerobject;otherwise,we createaWorkaholicobjectRecallthat,asaWorkaholicISAWorker,aWorkaholic canbeaccessedbyapointertoaWorkerAnymethodthatwemightcallforWorkerwillhavea meaningforWorkaholicobjectsPublicinheritanceautomaticallydefinesatypeconversion fromapointertoaderivedclasstoapointertothebase classWecandeclarethatwptrisapointertothebaseclassContinued….Thedecisionaboutwhichdoworktousecanbemadeat compiletimeoratruntimeIfthedecisionismadeatcompiletime,workersdowork mustbeusedbecausethatisthetypeof*wptratcompile timeIfwptrisactuallypointingatWorkaholic,thisdecisionis wrong.Becausethetypeofobjectthatwptrisactually pointingatcanbedeterminedonlyastheprogramruns, thisdecisionmustbemadeatruntimeAruntimedecisiontoapplythemethodcorrespondingto theactualreferencedobjectiscalleddynamicbindingContinued….Howeveraruntimedecisionincurssomeruntime overheadbecauseitrequiresthattheprogrammaintain extrainformationandthatthecompilergeneratecodeto performthetestThisoverheadwasoncethoughttobesignificantAlthoughotherlanguagessuchasSmalltalkand ObjectiveCusedynamicbindingbydefault,C++does notVirtualFunctionAvirtualfunctionusesdynamicbindingifacompiletime bindingdecisionisimpossibletomakeAnonvirtualfunctionwillalwaysusestaticbindingThedefaultisthatfunctionsarenonvirtual.Thiscondition isunfortunatebecausewenowknowthattheoverheadis relativelyminorAsaresult,anonvirtualfunctionshouldbeusedonly whenthefunctionisinvariantovertheinheritance hierarchyContinued….Virtualnessisinherited,soitcanbeindicatedinthebase classThusifthebaseclassdeclaresthatafunctionisvirtualthe decisioncanbemadeatruntime;otherwise,itismadeat compiletimeForexample Intheexceptionclass,thewhatmethodisvirtual.The derivedclassesrequirenofurtheractiontohavedynamic bindingapplyforwhatmethodcallsContinued….InlastexamplecodeofWorkclass,doWorkiscalledifit isdeclaredasvirtualIfdoworkisnotvirtualintheWorkerclass,butislater madevirtualinWorkaholic,thenaccessesthrough pointersandreferencestoWorkerwillstillusestatic bindingTomakearuntimedecision,thekeywordvirtualhaveto placeatthestartofthedoworkdeclarationintheWorker classinterfaceas classWorkerSummarizingTopicStaticbindingisusedbydefaultDynamicbindingisusedforvirtualfunctionsifthe bindingcannotberesolvedatcompiletimeHowever,aruntimedecisionisneededonlywhenan objectisaccessedthroughapointerorreferencetoabase classTypesofMemberFunctionThreetypesofmemberfunction Nonvirtualfunction Virtualfunction PurevirtualfunctionNonvirtualFunctionOverloadingisresolvedatcompiletimeToensureconsistencywhenpointerstoobjectsareusedWegenerallyuseanonvirtualmethodonlywhenthe functionisinvariantovertheinheritancehierarchyConstructorsarealwaysnonvirtualVirtualFunctionOverloadingisresolvedatruntimeThebaseclassprovidesadefaultimplementationthat maybeoverriddenbythederivedclassesDestructorsshouldbevirtualPureVirtualFunctionOverloadingisresolvedatruntimeThebaseclassprovidesnoimplementationandisabstractTheabsenceofadefaultrequireseitherthatthederived classesprovideanimplementationorthatthederived classesthemselvesbeabstractAbstractMethodAnabstractmethodisdeclaredinthebaseclassItalwaysdefinedinthederivedclassItsays(inthebaseclass),whatallclassobjectsinthe hierarchycandoandmusteventuallyimplementItdoesnotprovideadefaultimplementation,soeach derivedclassmustprovideitsownimplementationAbstractClassAclassthathasatleastoneabstractmethodiscalledan abstractclassThebehaviorofanabstractclassisnotcompletely defined,that’swhyabstractclassescanneverbe instantiatedWhenaderivedclassfailstooverrideanabstractmethod withanimplementation,themethodremainsabstractin thederivedclass ...

Tài liệu được xem nhiều: