OOP Concepts by Example

Embed Size (px)

Citation preview

  • 7/31/2019 OOP Concepts by Example

    1/5

    OOPConceptsbyExamplebyRandyCharlesMorinOflate,Ihavebeenwritingverynarrowfocusedarticlesthatexplainhowtoaccomplishthisorthattask.Manyofyouhavechangedyourquestionsfromthenarrowfocusofhow-toquestionstobroadertheorecticalquestions.OnequestionIgotlatelythatintriguemewastoexplaintheconceptsofOOPsshowingC++examples.Let'sstartbylayingdownsomegroundwork.IassumethatyouarefamilarwiththefollowingOOPconcepts;classes,objects,attributes,methods,types.Ifnot,thenthisarticlemightnotbeinyourrealm.I'dsuggeststartingwiththebasicconceptsofC++beforeyouattempttounderstandthemoreindepthconceptsthatI'llbediscussinginthisarticle.WhenwespeakofOOPconcepts,theconversationusuallyrevolvesaroundencapsulation,inheritanceandpolymorphism.ThisiswhatIwillattempttodescribeinthisarticle.InheritanceLetusstartbydefininginheritnace.Averygoodwebsiteforfindingcomputersciencedefinitionsishttp://www.whatis.com.Thedefinitionsinthisarticlearestolen

    fromthatwebsite.Definition:InheritanceInheritanceistheconceptthatwhenaclassofobjectisdefined,anysubclassthatisdefinedcaninheritthedefinitionsofoneormoregeneralclasses.Thismeansfortheprogrammerthatanobjectinasubclassneednotcarryitsowndefinitionofdataandmethodsthataregenerictotheclass(orclasses)ofwhichitisapart.Thisnotonlyspeedsupprogramdevelopment;italsoensuresaninherentvaliditytothedefined

    subclassobject(whatworksandisconsistentabouttheclasswillalsoworkforthesubclass).ThesimpleexampleinC++ishavingaclassthatinheritsadatamemberfromitsparentclass.classA{public:integerd;};classB:publicA{

    public:};TheclassBintheexampledoesnothaveanydirectdatamemberdoesit?Yes,itdoes.ItinheritsthedatamemberdfromclassA.Whenoneclassinheritsfromanother,itacquiresallofitsmethodsanddata.WecantheninstantiateanobjectofclassBandcallintothatdatamember.voidfunc()

  • 7/31/2019 OOP Concepts by Example

    2/5

    {Bb;b.d=10;};www.kbcafe.comCopyright2001-2002RandyCharlesMorinPolymorphismInheritanceisaveryeasyconcepttounderstand.Polymorphismontheotherhandismuchharder.Polymorphismisaboutanobjectsabilitytoprovidecontextwhenmethodsoroperatorsarecalledontheobject.Definition:PolymorphismInobject-orientedprogramming,polymorphism(fromtheGreekmeaning"havingmultipleforms")isthecharacteristicofbeingabletoassignadifferentmeaningtoaparticularsymbolor"operator"indifferentcontexts.Thesimpleexampleistwoclassesthatinheritfromacommonparentandimplementthesamevirtualmethod.classA{public:virtualvoidf()=0;

    };classB{public:virtualvoidf(){std::cout

  • 7/31/2019 OOP Concepts by Example

    3/5

    atom.Theobjectinterfaceconsistsofpublicmethodsandinstantiatedata.Protectionandinformationhidingaretechniquesusedtoaccomplishencapsulationofanobject.Protectioniswhenyoulimittheuseofclassdataormethods.Informationhidingwww.kbcafe.comCopyright2001-2002RandyCharlesMoriniswhenyouremovedata,methodsorcodefromaclass'spublicinterfaceinordertorefinethescopeofanobject.SohowarethesethreeconceptsimplementedinC++?You'llrememberthatC++classeshaveapublic,protectedandprivateinterface.Movingmethodsordatafrompublictoprotectedortoprivate,youarehidingtheinformationfromthepublicorprotectedinterface.IfyouhaveaclassAwithonepublicintegerdatamemberd,thentheC++definitionwouldbe...classA{public:integerd;};Ifyoumovedthatdatamemberfromthepublicscopeoftheprivatescope,theny

    ouwouldbehidingthemember.Bettersaid,youarehidingthememberfromthepublicinterface.classA{private:integerd;};Itisimportanttonotethatinformationhidingarenotthesameasencapsulation.Justbecauseyouprotectorhidemethodsordata,doesnotmeanyouareencapsulatingan

    object.Buttheabilitytoprotectorhidemethodsordata,providetheabilitytoencapsulateanobject.Youmightsaythatencapsulatingistheproperuseofprotectionandinformationhiding.Asanexample,ifIusedinformationhidingtohidemembersthatshouldclearlybeinthepublicinterface,thenIamusinginformationhidingtechniques,butIamnotencapsulatingtheclass.Infact,Iamdoingtheexactopposite(unencapsulatingtheclass).Donotgettheideathatencapsulationisonlyinformationhiding.Encapsulationisalotmore.Protectionisanotherwayofencapsulatingaclass.

    Protectionisaboutaddingmethodsanddatatoaclass.Whenyouaddmethodsordatatoaclass,thenyouareprotectingthemethodsordatafromusewithoutfirsthavinganobjectoftheclass.Inthepreviousexample,thedatamemberdcannotbeusedexceptasadatamemberofanobjectofclassA.Itisbeingprotectedfromuseoutsideofthisscenario.Ihavealsoheardmanycomputerscientistuseinformationhidingandprotectioninterchangeably.Inthiscase,thescientisttakesthemeaningofpro

  • 7/31/2019 OOP Concepts by Example

    4/5

    tectionandassignittoinformationhiding.Thisisquiteacceptable.AlthoughI'mnohistorian,Ibelievethedefinitionofinformationhidinghastakensometurnsovertheyears.ButIdobelieveitisstabilizingonthedefinitionIpresentedhere.AbstractionAnotherOOPconceptrelatedtoencapsulationthatislesswidelyusedbutgaininggroundisabstration.Definition:AbstractionThroughtheprocessofabstraction,aprogrammerhidesallbuttherelevantdataaboutanobjectinordertoreducecomplexityandincreaseefficiency.Inthesamewaythatabstractionsometimesworksinart,theobjectthatremainsisarepresentationoftheoriginal,withunwanteddetailomitted.Theresultingobjectitselfcanbereferredtoaswww.kbcafe.comCopyright2001-2002RandyCharlesMorinanabstraction,meaninganamedentitymadeupofselectedattributesandbehaviorspecifictoaparticularusageoftheoriginatingentity.

    Theexamplepresentedisquitesimple.Human'sareatypeoflandanimalandalllandanimalshaveanumberoflegs.TheC++definitionofthisconceptwouldbe...classLandAnimal{public:virtualintNumberOfLegs()=0;};classHuman:publicLandAnimal{public:virtualintNumberOfLegs(){return2;};

    };ThemethodNumberOfLegsinLangAnimalissaidtobeapurevirtualfunction.Anabstractclassissaidtobeanyclasswithatleastonepurevirtualfunction.HereIhavecreatedaclassLandAnimalthatisabstract.ItcanbesaidthattheLandAnimalclasswasabstractedfromthecommonalitybetweenalltypesoflandanimals,oratleastthosethatIcareabout.Otherlandanimalscanderivethereimplementationfromthesameclass.classElephant:publicLandAnimal{public:

    virtualintNumberOfLegs(){return4;};};AlthoughIcannotcreateaninstanceoftheclassLandAnimal,IcanpassderivedinstancesoftheclasstoacommonfunctionwithouthavingtoimplementthisfunctionforeachtypeofLandAnimal.boolHasTwoLegs(LandAnimal&x){return(x.NumberOfLegs()==2);

  • 7/31/2019 OOP Concepts by Example

    5/5

    };Thereisalsoalessrigiddefinitionofabstractionthatwouldincludeclassesthatwithoutpurevirtualfunctions,butthatshouldnotbedirectlyinstantiated.Amorerigiddefinitionofabstractioniscalledpurelyabstractclasses.AC++classissaidtobepurelyabstract,iftheclassonlycontainspurevirtualfunctions.TheLandAnimalclasswassuchaclass.Purelyabstractclassesareoftencalledinterfaces,protocolclassesandabstractbaseclasses.MoreConceptsAnothergrowingconceptinOOPisdynamicandstaticbinding.Mostlanguagesprovideoneortheother.C++providesboth.Amethodthatisnotvirtualissaidtobestaticallybound,whereasvirtualmethodsaresaidtobedynamicallybound.Non-virtualmethodsarestaticallybound,becausethebindingofthemethodisperformedatcompileandlinktimeandcannotbechanged.Virtualmethodsaredynamicallybound,becausethebindingofthemethodisactuallyperformedatrun-time.Whenyoucallavirtualmethod,

    asmalllookupisperformedintheobjectvirtualtable(a.k.a.vtable)tofindtheaddressofthemethodbeingcalled.Bymanipulatinganobjectsvtableatrun-time,thetargetaddresswww.kbcafe.comCopyright2001-2002RandyCharlesMorincanbealtered.FourothergrowingOOPconceptsarepersistance,concurrency,reflectionandobjectcomposition.Iwillnotdiscussthesehere,butmaybeinalaterarticle.Hopethisarticleprovesinformativeandthankyouforyourtime.