You are on page 1of 9

12/12/2012

CSC241:ObjectOrientedProgramming
LectureNo19

PreviousLecture
Defaultcopyconstructor Memorymanagement
Stringclassusingnew operator Pointertoobject Arrayofpointerstoobjects

Polymorphism Twoexamples
Animal:frog,fish,bird Shape:circle,triangle,rectangle
2

TodaysLecture
Polymorphism
Example Virtualfunction

Staticanddynamicbinding Abstractclassandpurevirtualfunctions

12/12/2012

Polymorphism Example2
Supposeyouhaveaobjectsofdifferent classes
Allareinheritedfromabaseclass youwanttoputthemallinanarray performaparticularoperationonthemusingthe samefunctioncall.
Shape

Circle

Square

Triangle
4

Cont.
shape*ptrArray[4]; ptrArray[0]=newCircle; ptrArray[1]=newTriangle; ptrArray[0]=newCircle; ptrArray[0]=newSquare; for(int j=0;j<4;j++) ptrarr[j]>draw();

0 1 2 3

*ptrArray
circle triangle circle square

Conditionforpolymorphism
Followingconditionmustbemeetinorderto achievepolymorphicbehaviour
First,allthedifferentclassesofshapes,suchas circleandtriangles,mustbeinheritedfroma singlebaseclass Second,thedraw()functionmustbedeclaredto bevirtual inthebaseclass.
Shape draw()

ptrarr[j]>draw();

Circle draw()

Square draw()

Triangle draw() 6

12/12/2012

Exampleprograms
NormalMemberFunctionsAccessedwith Pointers VirtualMemberFunctionsAccessedwith Pointers

NormalMemberFunctionsAccessed
classBase{ public: voidshow() {cout <<Base\n;} }; classDerv1:publicBase{ public: voidshow() {cout <<Derv1\n;} }; classDerv2:publicBase{ public: voidshow() {cout <<Derv2\n;} }; main(){ Derv1dv1; Derv2dv2; Base*ptr; ptr =&dv1; ptr>show(); ptr =&dv2; ptr>show(); } Gotoprogram

*ptr

dv1

dv2

ProgramOutput Base Base

Note:Compilerignoresthe contentsofthepointerptr and choosesthememberfunctionthat matchesthetypeofthepointer 8

Nonvirtualpointeraccess.

12/12/2012

VirtualMemberFunctionsAccessed
classBase{ public: virtualvoidshow() {cout <<Base\n;} }; classDerv1:publicBase{ public: voidshow() {cout <<Derv1\n;} }; classDerv2:publicBase{ public: voidshow() {cout <<Derv2\n;} }; main(){ Derv1dv1; Derv2dv2; Base*ptr; ptr =&dv1; ptr>show(); ptr =&dv2; ptr>show(); } Gotoprogram

*ptr

dv1

dv2

ProgramOutput Derv1 Derv2

Note:Compilerselectsthefunction basedonthecontentsofthe pointerptr,notonthetypeofthe 10 pointer

Virtualpointeraccess

11

Staticbinding
Whenamemberfunction/virtualfunctionis calledwiththeobjectofthatclass Forexample
dist1.getdist(); derv1.show(); base1.show();

Functioninvocationisresolvedatcompiletime. Thisiscalledstaticorearlybinding Thisisnotapolymorphicbehavior


12

12/12/2012

Dynamicbinding
Virtualfunctioncanbeinvokedusingbase classpointertoaderiveclassobject
shapePtr>draw()

Nowthecorrectderivedclassdrawfunction willbeselecteddynamically(executiontime) Thisiscalleddynamicorlatebinding Atruntime,whenitknowswhatclassis pointedbyshapePtr,thedrawfunctionofthat classiscalled


13

Allowableassignmentsb/wbaseand derivedclassobjectandpointer
Fourwaystoaimbaseandderiveclasspointer atbaseandderivedclassobjects
Baseclasspointertobaseclassobjects Derivedclasspointertoderivedclassobjects Baseclasspointertoderiveclassobjects
Deriveclassobjectisalsoobjectofbaseclass

Deriveclasspointertobaseclassobject.
Notallowed isarelationshipappliesonlyfromderiveclasstobase classnotviceversa
14

AbstractClassesandPureVirtualFunctions
classBase{ public: virtualvoidshow()=0; }; classDerv1:publicBase{ public: voidshow() {cout <<Derv1\n;} }; classDerv2:publicBase{ public: voidshow() {cout <<Derv2\n;} };

Purevirtual function

Gotoprogram

main(){ arr[2] Base*arr[2]; Derv1dv1; Derv2dv2; dv1 dv2 arr[0]=&dv1; arr[1]=&dv2; ProgramOutput arr[0]>show(); arr[1]>show(); Derv1 // Baseb; Derv2 }
15

Note:objectsofabstractclasscannotbecreated

12/12/2012

Note
Afteraimingabaseclasspointerataderived classobject,attemptingtoreferencederived classonlymemberswiththebaseclass pointerisacompilationerror
classB{ classDerv1:publicB{ public: public: virtualvoidshow()=0; voidshow() }; {cout <<Derv1\n;} voiddisplay() {cout<<helloderv1;} }; main(){ B*ptr; Derv1dv1; ptr =&dv1; ptr>show(); ptr>display(); }
16

Exampleprogram:Personclass
classperson { classprofessor:publicperson{ protected: private: charname[40]; int numPubs; public: public: voidgetName(){ voidgetData(){ cout <<Entername:; person::getName(); cin >>name; cout <<Enterpublications:; } cin >>numPubs; voidputName(){ } cout <<Nameis:<<name; bool isOutstanding(){ } return(numPubs >100)?true: virtualvoidgetData()=0; false; virtualbool isOutstanding()=0; } }; };
17

Cont.
classstudent:publicperson{ private: floatgpa; public: voidgetData(){ person::getName(); cout <<EnterGPA:; cin >>gpa; } bool isOutstanding(){ return(gpa >3.5)?true:false; } }; Gotoprogram person*persPtr[100]; int n=0; persPtr[n]=newstudent; persPtr[n]>getData(); n++; persPtr[n]=newprofessor; persPtr[n]>getData(); n++; for(int j=0;j<n;j++){ persPtr[j]>putName(); if(persPtr[j]>isOutstanding()) cout <<Thispersonis outstanding\n; }
18

12/12/2012

VirtualDestructors
Aproblemcanoccurwhenusing polymorphismtoprocessdynamically allocatedobjectsofaclasshierarchy E.g.applyingdeleteoperatortoabaseclass pointer,whichpointtoderivedclassobjects
B*ptr; Derv1dv1; ptr =&dv1; deleteptr;

Solution:virtualdestructor
19

Cont.
Avirtualdestructorinbaseclassmakesall derivedclassdestructorvirtual
B*ptr; Derv1dv1; ptr =&dv1; deleteptr;

Nowdestructorforappropriateclassiscalled Whenderivedclassobjectisdestroyed,base classpartofderiveclassobjectisalso destroyed Baseclassdestructorisexecutedafterderived classdestructor


20

Example virtualdestructor
classBase{ public: virtual ~Base()~Base() {cout <<Base destroyed\n;} }; classDerv:publicBase{ public: ~Derv() {cout <<Derv destroyed\n;} }; main(){ Base*pBase =newDerv; deletepBase; } WithoutvirtualDestructor Objectof *pBase Derv Objectof Derv ProgramOutput Basedestroyed WithvirtualDestructor *pBase ProgramOutput Dervdestroyed Basedestroyed Gotoprogram
21

Objectof Derv

12/12/2012

Virtualbaseclasses
Aproblemcanariseifamemberfunctionin theGrandchild classwantstoaccessdataor functionsintheParent class
When the Child1 and Child2 classes are derived from Parent, each inherits a copy of Parent; this copy is called a subobject
22

Cont.
classParent{ protected: int basedata; }; classChild1:publicParent {}; classChild2:publicParent {}; classGrandchild:publicChild1, publicChild2{ public: int getdata() {returnbasedata;} }; basedata

basedata

basedata

basedata Thissituationisambiguous,and thatswhatthecompilerreports


23

Cont.
classParent{ protected: int basedata; }; classChild1:virtualpublicParent {}; classChild2:virtualpublicParent {}; classGrandchild:publicChild1, publicChild2{ public: int getdata() {returnbasedata;} }; keywordvirtualinthese twoclassescausesthem toshareasinglecommon subobject oftheirbase classParent

Gotoprogram

24

12/12/2012

25

You might also like