You are on page 1of 22
Polymorphism systems Building Refinement _/ Object Relationships” Objectsand. 7 Classes C++ for C Programmers «Polymorphism 2 ‘Tavoking a Member Function 3 ‘Which Funetion is Called? 4 sDrawhacks of Barly Binding $ ‘Another Point of View 6 +An Objec-Oriented Approach 7 *vtrual Funetions 8 ‘Example of virua! Funetions 9 Example of Late Binding 10 ‘Displaying the Conteols 11 ‘Deletion of Subtypes 12 svimual Destructors 13 ‘iow Does Late Binding Work?! 14 ‘Tho Class Viable Mechanism (5 *Oigjeets and Late Binding 16 ‘Barly Binding virtual +Superfluous Funetion Definitions 18 ‘Pure virtual Functions 19 Summary 20 Guidelines 21 © QA Gropta, WA HAMDIOIT My Page ot Pobmopin Polymorphism * Objectives ~ To be ablo use polymorphism to distibute behaviour Incas hierarenioe + Contents ~ Member funetion invocation cum Cauppxy Pure vita! funtion + Praca al = Use polymorphiam to specialise class behaviour BBX, + Summary + Annex In the previous chapter, we sow how one class may he derived from another class in C++ ‘The detived class inert ll ofthe data members and member functions ofthe base cl886 and is free wo provide addtional features us appropriate. ‘The emphasis ofthe provious chapter was on how a buse elas ean he extended through derivation to provide new attributes and functiomlity. hn this Sense, inheritance ean be soon as. time-saving technique for the class quhor, singe it saves the author from having «0 define and implement de class from serach Inthis chapter we Hook at an exuemnly useful (eshnique called polymorphism, which allows itferet clases in a inhertance hierarchy to Be weated in exactly the same way a each other, /\se shal see ding the chapter polyoephisa i primaily intended te make the jb ese forthe clas ser. Polymorphism is one ofthe most powerfil concepts in objct- orien development anda got understanding is essential if you are going to get the most outer CH. Polymorphism i achieved In C++ by declaring member functions as vixreua in he base chase, Weesall examine the syntactic issues is some detail and outline some ofthe common ‘misconceptions and areas of dtficlty that aise when veut functions are used. We shal also discus the broader object-oriented issues and se how viz tual fuetions ae implemented by most modern-day C+ compiles. 2 QA Group Ld, -99DMIOOIT = Pree Dok ZT Poiymorpise Invoking a Meraber Function (lace contzot // guoeri sentroL fetter ttle eats coms poe eeonee yma ten Lostes =f "Sha atoe comes /) arts costal mtecatrets Srreliber Sresroils spent nowt): Trroughout the chapter, we shall be using a imple control hierarchy to illustrate the principles and practicalities of polymorphism in C-*. The contol class defined above acts 38 base lass Foe various different kinds of controls in 2 GUI application, such as seroll bars list hoses and comibo boxes. The control hase clas usa single function called show (). and he derived class ‘overrides this fanetion with its own Version of show (), AS We saw in the previous chapter, 4 derived class i a iberty’ to overt any’hase-clss functions that do not quite suit the purposes ofthe derived clas, Inthe eliont program, the user may create contro} objects and acrol Lar objects and invoke the show} function upon cach abject. The compiler decides which version of ‘show (0 call, based on the datatype ofthe abject on the leftchand side of the . operator. ‘As we shall soe shortly, this arrangement can become problematic when a large number of lasses appear inthe class hierarchy, each providing its own version ofthe how ¢) function. QA Groupe LS 9OMNOLT i) -Page Sot 2 Poeocpinm Which Function is Called? + The type of the object determines which function is. called ———F control nycontrol: ‘serolibar ayserolly ‘myconteod hoi)» sxyecrol1ohow(y * This is known as early or statle binding Clan ode dec whieh anton invoke by mroiig ped ooh Pert of the development ifeyele is the compile snd Tink phase, which ensues that as many potential problem es possible ae detected eto te aplication i shipped tthe cod ust One of the advantages ofa. compile-time language is fas programs, Ifyou Write a program thing a unime langoage the program as be interpret every ime W's execute ds ‘an be ume consuting: One ote inal design goats of Cot vas that it shold bean tient as Cs whic isl one oF the most eficent high-level languages in eistnes One ofthe effets of compile time code generation is thatthe compiles has fo decide which ‘ersion of a function shoul be called. A esl sce on the folowing page, ths can ‘Sometimes prove to be ite ieanccrins when an inheritance hierarchy fs Used Inthe example, mconerot isa hase clas object and wxyacx021 isa derivedelass object. The hace clas has a stiow () function, and the derived class ovens the function Swi-r mote specialized show () fonction to deal sith serll bas. When the show () function is called, the compiler decides which version ofthe function should be soko, based nthe dats ype appearing en he llidhand side of het => Inthe fis eo cases shoor, ss fairly Obvious which vosion of show 0 istequlred. The third and fourth examples ate moxe intresting and deserve closer examination. mmyeexoll .contxol: :show () “the myecro1l objet i a dervad-class object, bu the aser has specified thatthe base- class show) function s required. The compiler therefore mokes cont rol: sshow (). “hiss lowed ig Crs, because the derived class ier all ofthe capable of ts babe lis inelding the came ral “show function, Haves, the compiler dase not allow a statement such #s nycont oi. serellbax: sehow ) , becaise uycontrol ba base-lassobjct the only Fanetoms avaible to ave those defined in he OnE FE] Cass. (icontro1*)émyserol1) => abiow() “This example i extremely devious and speaks volumes fr the power and dangers of cas ‘operations n Ci! Tne address ofthe myserol abject is dermnined andthe pointer is then ‘Sonverted into a control pointer. Ihe compiles i fooled into inking the eect on the Te and sds ofthe > operators control abject and deides fo invoke the cone show) function. Needless to say. you are strongly discouraged rom Writing code like thst (© QA Geeup Lid, L3-998400017 8) Page oF (Ce ig a compiled language, rather than an interpreted rs such as Basi or Smalltalk Polymeric Drawbacks of Early Binding + Client code often deals with groups of similar objects Objects provie the same functions, but iferent implementations _ = The ollent cod has o decide whieh function to call = What Ht anew kind of contro is introduced? rp ome gw pcm £ < pestier Fonte Nola whew) ese oka anew) conse Pec ae Fe pid shor ay eto ante # Chit setolibars abort) _ suge"te object te a beeen ‘qi battens abort) ‘The inheritance hierarchy shown ubove is quite realistic. Many GUL class Hibarie provide a Similar set of contol classes. For example, dhe Borland OWL clas library provides the Jollowing contol classes, which represent the different kinds of child condols dat are most clten used ina dialog box. Most of these classes arc self explanatory: the only one which SJ might nex be familiar with s TVeseeont PON, which represents & Visual Basie custom onto a —— tH eceoflber ‘Taquge Tetepse Meouphox Toatoon Tamanteol 7 smashes nthe simplified hierarchy shown in the slide, each different derived cass provides its own ‘show () fiction, because each different onto is displayed in a diferent way. In dhe client program, the show_any_control () function takes a base-class pointer and tiesto display the control on the sereca using the appropriate show () function. As you may eocall from the previous chapter, C#+ allows a base-class pointer to hold the address of aderived-class objec, so the show_any_control () funetion could be called in any of the following ways: show_any_control (gagerollaar_ob}) ; show_any_control (gabutton_ob3}; ‘Thus, the pc argument in show_any_contvol () might be pointing to any kind of ‘control objet, und the function has to perform a switch statement of some kind to ‘determine which show |) fusction is requited. DOK Gray La LS. 9NOOOIT A) Page S082. Polymorph Another Point of View + Consider etd show any conteotieantest © pe) poses * Reconsider ‘pe-sahow(); ¢ Object decises wien tuneton teat “The example on the previous page illustrated he difficulies of eal Binding, wheraby the Compiler exaitnes the ype of ti objest on the lelthand side of he or “> operator {eeide thich function to cll. Problems ase because the type of the pointer is wot necessarily the same asthe typeof the chet is pointng to. For example a Comeeol potsier main fact be poiang oa Euston object. Which shew) Tunction would you expect the comple to cal Ih the show any! control () fnetion inthe sige above? ‘egaadless of what ype of object pis ely pointing (othe compile just ooks atthe data thpe of te pointer ise order to determine which sinew (| Junction to call: Since psi 2 Boncrol pointer, the eompilercals te contol; «slzow() funeion. This mish Comme as quite surprise i the unsuspecting wer sho calls how any control) with { dorived'elass object scrollbar mysexoll; J) peclare a scvollbar object shex_any_control(imyecroll); // Paes the object’s address into (7 the function. Te might come as a 7/ surprise when shox_any_contzel() 1) calls control: :show() Instead of (/ calling sorolibar: :show() ‘What we would like wo happen, of cous, i fo the choice of ebow () function tobe determined by he typeof the bject, rather than the typeof he pointer. Tiss the easence ‘polymorphism {a simple terms, polymomphism allows the lint program to send a message such 8 Show!) toany kindof contol occ such ava Derol bar ora button, and the object xteriines for iso wich version ofthe show fonction i require: the client program Sear kno orca whether tis dealing witha 2cro1 av, aboeton or whuleber “The Penetts of polymomptism cannot he understated. {© QA Grow Lis 63 99NHOI017 9) Page 6 of 21 Polymorphism An Object-Oriented Approach + Object interprets the message at runtime ~ Object knows what kins ot contro tis = object knows which show) focal + Known as late or dynamic binding _scroloar ad bation ar both kinds of contro! _ ps Meer smart tcoten 8) sexi el Polymorphism is appropriate when a base class has a number of functions what ae likely to be overridden in its derived classes. Functions that are common to al derived classes can be placed inthe base class, thereby serving asa general statement of the operations that may be applied to any of the derived classes. ‘The client program knows that whenever it has a hase-class pointe, iis safe 49 invoke one of these gencral functions upon the object in question, regardless of the exact datatype of the object. For example, if he pe pointer happens to be pointing to 2 sexo 1bar object, the elient program can safely invoke the ehow () function without knowing or caring ‘whether the sexo Lbar class has its own version of show (). Iitdoesn the control: :show |) Tanetion i alway’ thereto fallback on This process is known as fate binding or amie binding, since the decision as wo which version gf Show () shouldbe valled can only be determined at runtime, when the base-class pointer can be dereferenced o Fine out what Kind of object is involved “The benefits of late binding aretha it allows the cent program to write a single stacement such as the following to deal with any kind of control object inthe inheritance hierarchy. ~ pe->show(); vem ifa new derived classi introduced ata later dat, the statement will til pick up the ‘correet version of show) "The rest of the chapter shows how polymorphism is expressed in C+ and discusses the internal mechanisms used by most modern-day compilers to achieve the desived effect. ‘© QA Grp Li L3-9NOOOIT A) Page 7 of 21 Polymorphism virtual Functions + Achieve late binding by declaring a function as virtual i Pontes, : PtEstinE pots newts conaes fy! b + The derived class can inherit the function or override it chavs werottbax + pubes control | vote eouniaiati) conse e mod _ Reetensonare secur torment Lenser TET ts ett nw ent a J * This allows the client to use the correct show/() function neds naw the ect pe a oes, Inorder to achieve dynamic binding, all you have todo is declare the member function 1s ‘virtual inthe base class, as shown in the control class above. ‘The derived clas is not obliged to override the function if it doesn’t want to. For example, i swe define a new kind of cnttol called spinbat rem. for which the base function Conkror: shou") Is sulfieient, the epinbutton clas should be defined as follows: class spinbutton + public control i public 77 Bo not mention show() here - just inherit control: :show() h Ifthe derived clas does wish to override the show () function, the function has to be redeclared inthe derived class, with exactly the sume signature as the orginal function in the base clas, tis not strictly necessary to specify the virtual keyword inthe derived class: once fametion has becn declared vI'et ual in the base class, remains virtual Uyoughout the hicrarchy. Having said that, ii sili worthwhile using the vasreual keyword inthe derived class, because iceniphasises which fonctions are varfua1 (and use late binding} and which are fon-vL reual (and therefore use carly binding). The following example shows how virtual functions belave in comparison to non-viireual functions. clase control class scrollbar : public contrel { publict public ‘Virtual vold chow() const; virtual vold show{) const: void aet_foous()7 void set_focus(); be control * pe = new gorollhar; // Base-pointer to derived-class object pe->show() Yi) Lave binding £0 sexellbar::show() c-2get Focus!) + // early binding co BeneES ree lane) Y = BqA Groep Lad, 3 O90EDOOTT Ay Page BoD Pomorie Example of virtual Functions * Each subclass overrides the virtual show() function in sen subat te | Set cit 2 dcp ‘lane serolibes + patd control j clase button + vublie comtes} ‘ fe Pen tollbas (int, Sot! Pee cleo) Str vg ve sow ass api bg neve dal rane Nee ee ie a ea ae SE a ELE EETSL Shinty halts mana aces cot ior hae pape vine ety meee ae esas ng al is aM as NBS et Sa seas atin om een cen inc todos as yoraoedelSnd sana sincad inci * Litre er smi ml Amor odd ages ee neh Secon Gein a tee gear en Fe eee ee ade ae stat Bele kat he rus fn ew inn gga tis Thesovetther cdo nee stich greene nd en Tocca” waa eager e SEES choice gla ee ee see Phe fr dealing wid a ado baron has 4 dot nside H when its checked, whereas a check box ‘as en a ea sig a oe ene surfeit ie erecasverin be non sagebs cra yn SEACAANS MS las (© QA Group LAL 9ODATOOIT 9) Page oF 2 Polymorphism Exampte of Late Binding * Consider a function to display a dialog box to configure a mouse: Teta “mca Seed ecole arenas 26511~ 7) pene batten Hight Dh —) Having introduced the eevol bar and button classes on the previons page, the cade fragment shown above creates various objects of these types to representa dialog box on the sereen, As cach object is created, its constructor is called to initalse the data members in the object, bat tie control isnot displayed until the sox? () function is called. We shall see ‘now todo this on the following page. ‘The dialog box contains a scroll har and iso buttons, Tis purpose is to allow the user to ‘configure the mouse settings on the PC, Note: the client program is only interested in creating comerete control abjects such as button and scrollbar. The client program should not be allowed to create a control abject insolation. because the cant rot class i just a general hase clas for the connel hierarchy. Thus, the cont 01 class should have a pzetected consteveter fo prevent the user from ereaiing contol objects class cantyol // Rostract base clase { public virtual void showi) const; // Public interface protected; contror (+ (7 provected constructor (© QA Grom Lid, (L3. 9901000174) Pape Wot Potymorpisn Displaying the Controls + Late binding occurs when a virtual function is called through a base-class pointer pid elms oe betel, “tlate) casoae Jy forded contin et | al i | 2 ‘+ At runtime, p points to different kinds of control object “= The compilar cannot determine which show function to eal ~The docison is deferced until runtime The cont igure mouse () funetion town above Muses the benefits of vizeuad functions wo the client programmer. ‘The First important point that should be noticed is tha the ptab variable isan ata’ of base: ‘las porters. you wil reall, Ca allow ase-lane pointer to pont fo any Kind ot ‘derivdd-las objct tis allows the emeles inthe pe ab aeay to poin to diferent kinds of control ‘peab 0] pont tothe bae pur ofa sexo} bar object. pea] points 1 the hase par ofa button abc. pptabl2] points othe bse part ofa ut ton objet as well ‘Within the lop, temporary’ pointer called pis dared for notational simplicity. It would have en quite possible fo ache the same effect without using a temporary pointer atl _ for (ne i= 0) f= 3) rad peablij-sehow!) During the fint loop iteration, is pointing to the base pat of he e201 Lbax object. Since p ira cont fol pointer the comprlr looks atthe control clase definition and sees that |how {) Sevaeea This ela the compiler that late Binding is required saber than calling control: show () straightaway besuuse pis. a control pointer, the decision ‘ste deferred until tie, when the pointer eun be dereereneed find Out what kind ‘st ohjec it really posting. During th sscond Toop ration, wil be pointing tothe base past of a utt.on object, tindthe show) fimetn call will therefore be rsolved at rane to invoke the Bieronsatow |) fonction. This ite power of polymorphism. "The cnt program Goest need to wouty Whether p is pointing loa ez52 bar ora Button: the elient fam can Simply invoke therseual_ehonr() faction thenph a base- Fectbecvepten ; wae “The example shown above illustrates the viable mechanism as implemented by a typical C+ compiler ‘The control class has two virtual functions, so its vtable contains two entries. The first entry indicates which version of shor () should be called fora centa1 object, not surprisingly, this pointer just pins wo the cont-ro1: + show) function, Similarly, th sevond entfy in the table poines tothe stat of the cont rol renable') function ‘The gorol bax class is derived from contol and has its own viable, which indicates which versions of show() and enab1s () should be invoked lor serol Iba objects. Since the geroi Tae class provides its own show |) and enable () functions the entries in the BCxoT Lbar vable point to these new Functions rather chan Wo the original {nctions defined in the base cl ‘The button clas is also derived from contre, and it too hus its own vuable. Since the gantzel vigble has tvo ents, the but ton stable wil also have a least two entries: the first entry indicates which version of show () should he called fora bat ton object, whilst the sseond entry tells us sthieh version of enable (> is approprat. (Clearly, the first entry in the viable should point the Rut ton: sahow() function, Decauie the but Eon class hus chosen to override ube show () function. What about the second entry in the vtble? The but ton class docs not override the snabLe () Function. Instead, it chooses to inherit the cont rol : ;enable () function from the base class Therefore if enabze () fipeton is aed upon burton objet the viable el should ensure that the control: :enable/) funetion is invoked. Tn other words, Second entry inthe Dut ton viable should point tothe control: enable () function, ‘©. O4 Group Lig L3-99040017 Page 15 of 2E Potymoephism Objects and Late Binding FB] pees ene eee anwiy Lo Sea scaey co coaties + py Sy le epel004 f scsoiseer Jo ef satan atone coe scranibar epeedlo.355)1 Having seen how the compiler sets up the vables for clases that contain vazeua functions al thot erin sto consider ow these wes are oad a rrie 0 {termine which function ges cle. “The side shows de afferent viales one forthe cont-z01 lass, ane forte Button lass ad another forthe sozolLbar clsss, Each vable comin two enties, sine each of the asses contains two vitae fnctions, The code fragment shows te differen contol objets beng created, Each object contains {Lapscial member called a situa able pointer (or tr for shot, which denies the able {hat shouldbe used for is objet For example, the objets called Let and right are but ton objets, so thet vps point tothe button stable. Simlely the pozol bar object called ope has 2 pu tat points fothe geval bay aH. Leta consider he sequence of events hen he Show (fonction is invoke throvgh the Bases pointer called. The compitr realises ari ting tere bese hoe) Tun sdesiedas vaeteal ie “At rantime, the potr is dereferenes! to find ou which abet sheng pointe to. In this parueular cave pi pointing whe bat Con object called rigs. Te objects vps then Examined to find out wich vtable should be used fo this paricular objet. Once we gc {he appropeiate stable, the relevant Tanto: pointer entry m he table canbe consulted 10 {nsoB€ the core version of S04! “Ths, the process of eynamie binding involves two exe pointer dereerences an is ‘herefore marginally leslie than a conventional furetion ell: However this overbead ‘Rs isighfeant haat canbe ipnored in racial terms Furthermore, the overhead only applies to virtual functions: on-vi-tua functions do ‘ov incur tis overlead This in Ur helps fo gxplsn why clases don’t just declare all ofthe ember funedons as vixetats every ange function cal cused hs penal he {verhead might sat o Become noticeable Noe: an objec only contains vp if its lass or any’of its ase classes has a via Titcion. For exaupe the Gate els ntraduced cari the course den thave ay virtual functions at all. so the date class does not have a viable and dat. objects do Nothaseavpiremy QA Grp LS 9PNOODIT Page 62 Polymuerin Early Binding virtual Functions + Late binding requires a base-class pointer + Early binding can still occur with virtual functions: ‘tase sonerot t | fate. Gleuat votd show’) const; YOsd client (eontvol + per) scrollbar myscrol1; Ss myueroll.ehew() 7 “pes panon Of bezsseontrolszhow() + wr epi cahow (hy Laie binding is achieved by declaring a Function ay waebUaT Th the base Glass, then InvOKing _ the function thraugh a baao-clas point As we have soon on the lst Few pages the process Of tuntime function resolution is wafeinlly loss efficient than ah eally-bound tunction cal, because ofthe extra pointer aperations that have tebe performed. “There area few situations in C++ where the compiler has enough information a its disposal 1 reiolve a-virenal function call at compile ime, rather than baving to wait uni runtime to make the decision, The compir always prfers io resalve funetion calls sing early binding if ean, Because is move efliient than late binding fo the example shown above, the conto! base clas hus a Vireuat funeton called show (). and the olLene function aa invokes show (} in a number of varied and interesting ways. Which of the function calls can De resolved at compile time and which must be defeated until runtime? nyscroll.show (} In this eae, tere Is mo Jou whatsoever tht the object involved iy a sex01 bax object, xo the compiler uses camy binding and calls Sero1 baw: :enow()~ The vables do not need to ‘he consid inthis case. per->ehew() ‘There is no way that the compiler can determine what kind of eject per is really pointing this eun only be established at runtime, when the objets vptr can be examined wo See which ‘lable should he used. Therefore, this function will be resolve dynariically using late binding, via the appropriate viable per-seontzol :sshow) {In this case, the cient program has specified that the base-clss function control : - shew () Js required, regardless of the type of object ptr happens to be pointing to, This decision is - ‘made at compile time und does not require runtime viable lookup. (per! show()r This examplo is exactly the same as the second esample describod above, _ is simply a shorthand nolalion for (pez) - chow |) Note: do.nor call virtual functions inside a constructor «the base-cass version of a ‘virtual function isalways called inside a constructor (effectively the viable hasnt yet been Sel up to ciliate true dynamic binding) © QA Group Ld (L3 996490017) Page 17 uf24 we pee->enowl) Polynepise Superfluous Function Definitions + Some base classes represent a high-level view of reality GS ay meen nmtcoern ‘ We never ereato mammal objects i | cuecenrano oni oat 1 Se + Base class provides virtual functions elas nema ~ Often thers is no gonsrakpurpose e funetonalty te b9a0 class can provide ~ Each derived class proves its own implementation ‘To close the chapter, consider the situation shown above, in which the base class wishes 10 declare a few ‘eet lial functions such a¢ eat () and 8129p |), but Joestt wish provide any implemsyetio or th fancuons mth bse cas. The oly reason hess functions are declared inthe Base class all ¢9 reserve cnties for these funetions inthe tvatwnial stable, sheeby ensuring thatthe funcuons are resolved at runlume using late binding, ‘Te iden is shat he hase class specifies the interface for these funedions, but relies on the derived classes to provide the implementation details, In other words, there is no sensible ‘default behaviout that can be placed in the buso-clas versions of these functions How ean we declare a virtual function inthe base class i the function doesn’t have any ‘ecognised behaviour? One possible solution might be to declare a do-nothing vireual fnetion as follows: ‘clase waned // Baze-clase definition { public ‘virtual vold eat() // Declare a do-acthing virtual function uy ht ‘This approach stisis the imma need to esr alain ie abe forthe eat ( Tins butts sl pot gate gd enough ds apse Jatt fore the deve lasso ttm te Hunton and provide an implonematon forthe eS) uncon Gov cat # pubic mammal /) Devivedsclase definition t publics U/ The devived clase Len’t obliged to override the eat () funetion W/ AE de dosen't want to; it can inherit the de-nothing eat () / function from the wanmal bso class. Thie is not what ve want! BGA Grom a (L3 990400017 A) Page 18 oF Potymon nie Pure virtual Functions. ++ The class designer can specify functions as “undefined” i a rcist void enti Derived classes provide the implementation pests atte meet Pe ctoaat vata ext) _ vibeaal vesd sleep wold catesateee Leaner d - ‘To solution tothe dilemme outlined on the previous page is to use a tehnigue known as “pure virtual functions", ts shown above, & pure virtuad function specified using the following syntuxin the buse-class definition: clase base_clase_1 ~ { public virtual yoid pure_virtuai_tune() - 0; . h "This reserves an entry in the viable, just like a normal virtua funetion, but che entry in this ease ise null pointer, This indicates tha dhe function name is recognised, but that mo Implementation is provided by the base class, ‘A class that contains one or more pure virtua funetions is, by definition, un sbstract lass. In other words, the compiler does not allow such objects io be created in the client Dyogram, The ean fr hse Fay aarp the compe et you rele Such an objet, you might be tempted @ invoke one of is pure vie ual. funedonss base_class_nane disaetercbj; _// If we could create this object, disasterop].pure_virtual_tunc(); // we could then try to invoke one — (// of the pure virtual functions ~ 41 these Functions have no body! ‘The derived clases are obliged 1o override all ofthe pure vi:=we functions declared in — the base class. Ifthe derived clas fails to do so, then i too becomes an abstoct class amd ‘anor e instantiated in the client program cites. ‘© QA Groep Lid (L3-99040U017 i) Page 19 oF 21 Pyarpivn Summary + In C++, polymorphism is achieved by dectaring functions as virtual in the base class ‘+ The client code is relieved of the task of identifying the exact type of the object + Furthermore, the client code is unmodified if new ‘subtypes are added + Abstract base classes may be declared by ‘specifying pure virtual functions in the base class Polymorphism is one ofthe most powerful cancepts in object-oriented technology. Itallows. the client program to deal with large inheritance hierarchies in a considerably simplified manner: the client program ean simply send 8 message to an object and feave the abject to decide for itself which version ofthe function in the hierarchy should be invoked, Furthermore, the client program is unchanged if a new clus is added tothe hierarchy at 2 later date. The new clas fits seamlessly into the hierarchy without causing major headaches to the class user. Polymorphist is achieved in C++ by declaring a function as vital in the base cass ‘This causes the compiler to generate a virtual function table (or vtable fr the class, which Indicates the appropriate set of functions forthe class, Each object of such a class contains a hidden data member called vttual funetion pointer ‘or vpn), which acts as a selector to determine Which veal to use for this Fype of abject. Atte end ofthe chapter, we discussed the meaning of pure v4 rua functions und saw Drow they might be useful in specifying an abstract base-clas definidon © GA Group Ld (L3-990H00017 8) Pa Palymophin, + Override virtual functions to have semantics compatible ‘with those in the base class Non-public destructors should be declared virtual in base classes Avoid calling virtual functions in constructors and destructors ~ Especialy pure viral functions! Inlining Is generally ignored with virtual functions. ‘Only base classes should have virtual functions Declare abstract base class constructors protected © QA Grp Lad L3. 980400017 4) Page 24k 2

You might also like