• Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
469
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
28
Comments
0
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. OOP COMPLETE NOTESBYUmer Tanvir
  • 2. CSC241:Object OrientedProgrammingSpring 20131. Starting OOPMay25,2013COMSATSInstituteofInformationTechnology2Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 3. Study Assignment• I hope you did go through chapter 1 of both the books.• How was the experience?• What did you learn?May 25, 2013 COMSATS Institute of Information Technology 3
  • 4. Procedural vs. Object-Oriented• ProceduralWithdraw, deposit, transfer• Object OrientedCustomer, money, accountMay 25, 2013 COMSATS Institute of Information Technology 4
  • 5. Object-Orientation(OO)May 25, 2013 COMSATS Institute of Information Technology 5
  • 6. What is Object-Orientation?• A technique for system modeling• OO model consists of several interacting objectsMay 25, 2013 COMSATS Institute of Information Technology 6
  • 7. What is a Model?• A model is an abstraction of something• Purpose is to understand the product before developing itMay 25, 2013 COMSATS Institute of Information Technology 7
  • 8. Examples – Model• Highway maps• Architectural models• Mechanical modelsMay 25, 2013 COMSATS Institute of Information Technology 8
  • 9. Example – OO ModelMay 25, 2013 COMSATS Institute of Information Technology 9
  • 10. …Example – OO Model• Objects• Ali• House• Car• Tree• Interactions• Ali lives in the house• Ali drives the carMay 25, 2013 COMSATS Institute of Information Technology 10AliCarHouseTreelives-indrives
  • 11. Object-Orientation - Advantages• People think in terms of objects• OO models map to reality• Therefore, OO models are• easy to develop• easy to understandMay 25, 2013 COMSATS Institute of Information Technology 11
  • 12. What is an Object?An object is• Something tangible (Ali, Car)• Something that can be apprehended intellectually (Time, Date)May 25, 2013 COMSATS Institute of Information Technology 12
  • 13. … What is an Object?An object has• State (attributes)• Well-defined behaviour (operations)• Unique identityMay 25, 2013 COMSATS Institute of Information Technology 13
  • 14. Example – Ali is a Tangible Object• State (attributes)• Name• Age• behaviour (operations)• Walks• Eats• Identity• His nameMay 25, 2013 COMSATS Institute of Information Technology 14
  • 15. Example – Car is a Tangible Object• State (attributes)- Color- Model• behaviour (operations)- Start Car- Accelerate- Change Gear• Identity- Its registration numberMay 25, 2013 COMSATS Institute of Information Technology 15
  • 16. Example – Time is an Object ApprehendedIntellectually• State (attributes)- Hours - Seconds- Minutes• behaviour (operations)- Set Hours - Set Seconds- Set Minutes• Identity- Would have a unique ID in the modelMay 25, 2013 COMSATS Institute of Information Technology 16
  • 17. Example – Date is an Object ApprehendedIntellectually• State (attributes)- Year - Day- Month• behaviour (operations)- Set Year - Set Day- Set Month• Identity- Would have a unique ID in the modelMay 25, 2013 COMSATS Institute of Information Technology 17
  • 18. Definition• What Is an Object?• An object is a software bundle of related variables and methods.Software objects are often used to model real-world objects you findin everyday life.• Objects are key to understanding object-oriented technology. You canlook around you now and see many examples of real-world objects:dog, desk, television set, bicycle.May 25, 2013 COMSATS Institute of Information Technology 18
  • 19. Real-world objects share two characteristics• They all have state and behavior• dogs have state (name, color, breed, hungry) and behavior (barking,fetching, and wagging tail).• Bicycles have state (current gear, current pedal cadence, two wheels,number of gears) and behavior (braking, accelerating, slowing down,changing gears).May 25, 2013 COMSATS Institute of Information Technology 19
  • 20. Software objects are modeled after real-worldobjects• A software object maintains its state in one or more variables .• A software object implements its behavior with methods . A methodis a function (subroutine) associated with an object.May 25, 2013 COMSATS Institute of Information Technology 20
  • 21. Can represent real-world objects by usingsoftware objects.• You might want to represent real-world dogs as software objects in ananimation program or a real-world bicycle as a software object in theprogram that controls an electronic exercise bike.• You can also use software objects to model abstract concepts. Forexample, an event is a common object used in GUI window systems torepresent the action of a user pressing a mouse button or a key onthe keyboard.May 25, 2013 COMSATS Institute of Information Technology 21
  • 22. Moving to new thinking …• C is a procedural language. A procedure is a list ofinstructions.• Very small programs (tens of lines) need no organization.• As they get large (hundreds of lines), they are divided intofunctions.• Functions are still lists of instructions.• Dividing a program into functions gives a structure to theprogram (hence structured programming).May 25, 2013 COMSATS Institute of Information Technology 22
  • 23. Moving to new thinking …• C programming cannot do the following well:• Functions have unrestricted access to global data.• Data and Functions are unrelated; they do not form alogical group or show any form of binding.• Cannot model ‘real world’.• In real world, we deal with objects like cars, peopleetc.• Are such objects like ‘data’? Which data type describes acar, for example?• Are such objects like ‘functions’? What will a function car()do?May 25, 2013 COMSATS Institute of Information Technology 23
  • 24. Moving to new thinking …• A real world object, e.g. car:• Is its description purely the ability to have a ‘data type’ torepresent its specifications or ‘attributes’ only? Forexample what attributes describe a car?• So by having all these attributes ‘only’ do you know allabout a car? Would you buy a car by merely looking atthese attributes and their values?• No! What else do you wish to have?May 25, 2013 COMSATS Institute of Information Technology 24
  • 25. Moving to new thinking …• A real world object, e.g. car:• Test drive! Right?• What would you know through a test drive: how it‘behaves’ in response to various stimulus!• How can it negotiate a speed braker, a speedy turn, full brakingetc.• Effectively, you wish to know how it ‘functions’.• Behaviour is like a function.• So neither data nor functions, by themselves, modelreal-world objects effectively.May 25, 2013 COMSATS Institute of Information Technology 25
  • 26. Object Oriented Approach …• Neither data nor functions, by themselves, model real-world objects effectively.• OO languages (like C++) combine both ‘data’ and‘functions that operate on that data’ into a single unit,called ‘object’. Hence ‘encapsulating’ an entity.• The objects functions are called member functions.• Typically, data can be accessed through functions only. Sodata gets ‘hidden’.• Data hiding ensures the data is not accidentally altered.• Reference analogy of a growing company; 2 people vs 100employee company.• Objects communicate with each other by calling eachother’s member functions.May 25, 2013 COMSATS Institute of Information Technology 26
  • 27. Object Oriented Approach …• OOP is all about ‘organization’ and not about programoperation. Most individual statements are similar to Cstatements. Member functions may be very similar toC procedural functions.• In C you used to think about functions.• In C++ you should think about objects.• Often objects in C++ are real-world analogies.• In C++ objects are ‘instances’ of ‘classes’. E.g. HondaCity is an instance of class car!• Class serves as a cookie cutter and an object a cookie.May 25, 2013 COMSATS Institute of Information Technology 27
  • 28. Abstraction• Abstraction is a way to cope with complexity.• Principle of abstraction:“Capture only those details about an object that are relevant to currentperspective”May 25, 2013 COMSATS Institute of Information Technology 28
  • 29. Example – Abstraction• Attributes- Name - Employee ID- Student Roll No - Designation- Year of Study - Salary- CGPA - AgeMay 25, 2013 COMSATS Institute of Information Technology 29Ali is a PhD student and teaches BS students
  • 30. Example – Abstraction• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - WalkMay 25, 2013 COMSATS Institute of Information Technology 30Ali is a PhD student and teaches BS students
  • 31. Example – AbstractionAttributes• - Name - Employee ID• - Student Roll No - Designation• - Year of Study - Salary• - CGPA - AgeMay 25, 2013 COMSATS Institute of Information Technology 31Student’s Perspective
  • 32. Example – Abstraction• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - WalkMay 25, 2013 COMSATS Institute of Information Technology 32Student’s Perspective
  • 33. Example – Abstraction• Attributes- Name - Employee ID- Student Roll No - Designation- Year of Study - Salary- CGPA - AgeMay 25, 2013 COMSATS Institute of Information Technology 33Teacher’s Perspective
  • 34. Example – Abstraction• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - WalkMay 25, 2013 COMSATS Institute of Information Technology 34Teacher’s Perspective
  • 35. Example – Abstraction• Ordinary PerspectiveA pet animal with• Four Legs• A Tail• Two Ears• Sharp Teeth• Surgeon’s PerspectiveA being with• A Skeleton• Heart• Kidney• StomachMay 25, 2013 COMSATS Institute of Information Technology 35A cat can be viewed with different perspectives
  • 36. Example – AbstractionMay 25, 2013 COMSATS Institute of Information Technology 36Driver’s ViewEngineer’s View
  • 37. Abstraction – Advantages• Simplifies the model by hiding irrelevant details• Abstraction provides the freedom to defer implementation decisionsby avoiding commitment to detailsMay 25, 2013 COMSATS Institute of Information Technology 37
  • 38. Classes• In an OO model, some of the objects exhibit identical characteristics(information structure and behaviour)• We say that they belong to the same classMay 25, 2013 COMSATS Institute of Information Technology 38
  • 39. Example – Class• Ali studies mathematics• Anam studies physics• Sohail studies chemistry• Each one is a Student• We say these objects are instances of the Student classMay 25, 2013 COMSATS Institute of Information Technology 39
  • 40. Example – Class• Ahsan teaches mathematics• Aamir teaches computer science• Atif teaches physics• Each one is a teacher• We say these objects are instances of the Teacher classMay 25, 2013 COMSATS Institute of Information Technology 40
  • 41. Graphical Representation of ClassesMay 25, 2013 COMSATS Institute of Information Technology 41(Class Name)(attributes)(operations)(Class Name)Normal FormSuppressedForm
  • 42. Example – Graphical Representation ofClassesMay 25, 2013 COMSATS Institute of Information Technology 42CirclecenterradiusdrawcomputeAreaNormal FormSuppressedFormCircle
  • 43. Example – Graphical Representation ofClassesMay 25, 2013 COMSATS Institute of Information Technology 43PersonnameagegendereatwalkNormal FormSuppressedFormPerson
  • 44. Inheritance• A child inherits characteristics of its parents• Besides inherited characteristics, a child may have its own uniquecharacteristicsMay 25, 2013 COMSATS Institute of Information Technology 44
  • 45. Inheritance in Classes• If a class B inherits from class A then it contains all the characteristics(information structure and behaviour) of class A• The parent class is called base class and the child class is calledderived class• Besides inherited characteristics, derived class may have its ownunique characteristicsMay 25, 2013 COMSATS Institute of Information Technology 45
  • 46. Example – InheritanceMay 25, 2013 COMSATS Institute of Information Technology 46PersonTeacherDoctorStudent
  • 47. Example – InheritanceMay 25, 2013 COMSATS Institute of Information Technology 47ShapeCircleTriangleLine
  • 48. Inheritance – “IS A” or“IS A KIND OF” Relationship• Each derived class is a special kind of its base classMay 25, 2013 COMSATS Institute of Information Technology 48
  • 49. Example – “IS A” RelationshipMay 25, 2013 COMSATS Institute of Information Technology 49PersonnameagegendereatwalkTeacherdesignationsalaryteachtakeExamStudentprogramstudyYearstudyheldExamDoctordesignationsalarycheckUpprescribe
  • 50. Example – “IS A” RelationshipMay 25, 2013 COMSATS Institute of Information Technology 50ShapecolorcoorddrawrotatesetColorCircleradiusdrawcomputeAreaLinelengthdrawTriangleangledrawcomputeArea
  • 51. Inheritance – Advantages• Reuse• Less redundancy• Increased maintainabilityMay 25, 2013 COMSATS Institute of Information Technology 51
  • 52. Reuse with Inheritance• Main purpose of inheritance is reuse• We can easily add new classes by inheriting from existing classes• Select an existing class closer to the desired functionality• Create a new class and inherit it from the selected class• Add to and/or modify the inherited functionalityMay 25, 2013 COMSATS Institute of Information Technology 52
  • 53. Example ReuseMay 25, 2013 COMSATS Institute of Information Technology 53ShapecolorcoorddrawrotatesetColorCircleradiusdrawcomputeAreaLinelengthdrawTriangleangledrawcomputeArea
  • 54. Example ReuseMay 25, 2013 COMSATS Institute of Information Technology 54PersonnameagegendereatwalkTeacherdesignationsalaryteachtakeExamStudentprogramstudyYearstudyheldExamDoctordesignationsalarycheckUpprescribe
  • 55. Example ReuseMay 25, 2013 COMSATS Institute of Information Technology 55PersonnameagegendereatwalkTeacherdesignationsalaryteachtakeExamStudentprogramstudyYearstudyheldExamDoctordesignationsalarycheckUpprescribe
  • 56. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May25,2013COMSATSInstituteofInformationTechnology56
  • 57. ThanksMay 25, 2013 COMSATS Institute of Information Technology 57
  • 58. CSC241:Object OrientedProgrammingSpring 20131. Inheritance & GeneralizationMay25,2013COMSATSInstituteofInformationTechnology58Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 59. Recap – Inheritance• Derived class inherits all the characteristics of the base class• Besides inherited characteristics, derived class may have its ownunique characteristics• Major benefit of inheritance is reuseMay 25, 2013 COMSATS Institute of Information Technology 59
  • 60. Concepts Related with Inheritance• Generalization• Subtyping (extension)• Specialization (restriction)May 25, 2013 COMSATS Institute of Information Technology 60
  • 61. Generalization• In OO models, some classes may have common characteristics• We extract these features into a new class and inherit original classesfrom this new class• This concept is known as GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 61
  • 62. Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 62CirclecolorverticesradiusmovesetColorcomputeAreaLinecolorverticeslengthmovesetColorgetLengthTrianglecolorverticesanglemovesetColorcomputeArea
  • 63. Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 63ShapecolorverticesmovesetColorCircleradiuscomputeAreaLinelengthgetLengthTriangleanglecomputeArea
  • 64. Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 64TeachernameagegenderdesignationsalaryteachtakeExameatwalkStudentnameagegenderprogramstudyYearstudyheldExameatwalkDoctornameagegenderdesignationsalarycheckUpprescribeeatwalk
  • 65. Example – GeneralizationMay 25, 2013 COMSATS Institute of Information Technology 65PersonnameagegendereatwalkTeacherdesignationsalaryteachtakeExamStudentprogramstudyYearstudyheldExamDoctordesignationsalarycheckUpprescribe
  • 66. Sub-typing & Specialization• We want to add a new class to an existing model• Find an existing class that already implements some of the desiredstate and behaviour• Inherit the new class from this class and add unique behaviour to thenew classMay 25, 2013 COMSATS Institute of Information Technology 66
  • 67. Sub-typing (Extension)• Sub-typing means that derived class is behaviourally compatible withthe base class• Behaviourally compatible means that base class can be replaced bythe derived classMay 25, 2013 COMSATS Institute of Information Technology 67
  • 68. Example –Sub-typing(Extension)May 25, 2013 COMSATS Institute of Information Technology 68PersonnameagegendereatswalksStudentprogramstudyYearstudytakeExam
  • 69. Example –Sub-typing(Extension)May 25, 2013 COMSATS Institute of Information Technology 69ShapecolorverticessetColormoveCircleradiuscomputeCFcomputeArea
  • 70. Specialization (Restriction)• Specialization means that derived class is behaviourally incompatiblewith the base class• Behaviourally incompatible means that base class can’t always bereplaced by the derived classMay 25, 2013 COMSATS Institute of Information Technology 70
  • 71. Example – Specialization(Restriction)May 25, 2013 COMSATS Institute of Information Technology 71Personage : [0..100]…Adultage : [18..100]…setAge( a )…setAge( a )…age = aIf age < 18 thenerrorelseage = a
  • 72. Example – Specialization(Restriction)May 25, 2013 COMSATS Institute of Information Technology 72IntegerSet…NaturalSet…add( elem )…add( elem )…add elementto the setIf elem < 1 thenerrorelseadd elementto the set
  • 73. Overriding• A class may need to override the default behaviour provided by itsbase class• Reasons for overriding• Provide behaviour specific to a derived class• Extend the default behaviour• Restrict the default behaviour• Improve performanceMay 25, 2013 COMSATS Institute of Information Technology 73
  • 74. Example – Specific BehaviourMay 25, 2013 COMSATS Institute of Information Technology 74ShapecolorverticesdrawmovesetColorCircleradiusdrawcomputeAreaLinelengthdrawTriangleangledrawcomputeArea
  • 75. Example – ExtensionMay 25, 2013 COMSATS Institute of Information Technology 75WindowwidthheightopenclosedrawDialogBoxcontrolsenabledraw1- Invoke Window’sdraw2- draw the dialogbox
  • 76. Example – RestrictionMay 25, 2013 COMSATS Institute of Information Technology 76IntegerSet…NaturalSet…add( elem )…add( elem )…Add element tothe setIf elem < 1 thengive errorelseAdd element tothe set
  • 77. Example – Improve Performance• Class Circle overridesrotate operation of classShape with a Nulloperation.May 25, 2013 COMSATS Institute of Information Technology 77ShapecolorcoorddrawrotatesetColorCircleradiusdrawrotate
  • 78. Abstract Classes• An abstract class implements an abstract concept• Main purpose is to be inherited by other classes• Can’t be instantiated• Promotes reuseMay 25, 2013 COMSATS Institute of Information Technology 78
  • 79. Example – Abstract Classes• Here, Person is an abstract classMay 25, 2013 COMSATS Institute of Information Technology 79TeacherDoctorStudentPersonnameagegendereatwalk
  • 80. Example – Abstract Classes• Here, Vehicle is an abstract classMay 25, 2013 COMSATS Institute of Information Technology 80BusTruckCarVehiclecolormodelaccelerateapplyBrakes
  • 81. Concrete Classes• A concrete class implements a concrete concept• Main purpose is to be instantiated• Provides implementation details specific to the domain contextMay 25, 2013 COMSATS Institute of Information Technology 81
  • 82. Example – Concrete Classes• Here, Student, Teacher and Doctor are concreteclassesMay 25, 2013 COMSATS Institute of Information Technology 82TeacherDoctorStudentprogramstudyYearstudyheldExamPerson
  • 83. Example – Concrete ClassesMay 25, 2013 COMSATS Institute of Information Technology 83• Here, Car, Bus and Truck are concrete classesBusCarVehicleTruckcapacityloadunload
  • 84. Multiple Inheritance• We may want to reuse characteristics of more than one parent classMay 25, 2013 COMSATS Institute of Information Technology 84
  • 85. Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 85Mermaid
  • 86. Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 86MermaidWoman Fish
  • 87. Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 87Amphibious Vehicle
  • 88. Example – Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 88Amphibious VehicleLand Vehicle Water VehicleVehicleCar Boat
  • 89. Problems with Multiple Inheritance• Increased complexity• Reduced understanding• Duplicate featuresMay 25, 2013 COMSATS Institute of Information Technology 89
  • 90. Problem – Duplicate Features• Which eat operation Mermaid inherits?May 25, 2013 COMSATS Institute of Information Technology 90MermaidWoman Fisheat…eat…
  • 91. Solution – Override the Common FeatureMay 25, 2013 COMSATS Institute of Information Technology 91MermaidWoman Fisheat…eat…eat…Invoke eatoperation ofdesired class
  • 92. Problem – Duplicate Features(Diamond Problem)• Which changeGear operation Amphibious Vehicleinherits?May 25, 2013 COMSATS Institute of Information Technology 92Amphibious VehicleLand Vehicle Water VehicleVehicleCar BoatchangeGear
  • 93. Solution to Diamond Problem• Some languages disallow diamond hierarchy• Others provide mechanism to ignore characteristicsfrom one sideMay 25, 2013 COMSATS Institute of Information Technology 93
  • 94. Association• Objects in an object model interact with each other• Usually an object provides services to several other objects• An object keeps associations with other objects to delegate tasksMay 25, 2013 COMSATS Institute of Information Technology 94
  • 95. Kinds of Association• Class Association• Inheritance• Object Association• Simple Association• Composition• AggregationMay 25, 2013 COMSATS Institute of Information Technology 95
  • 96. Simple Association• Is the weakest link between objects• Is a reference by which one object can interact with some otherobject• Is simply called as “association”May 25, 2013 COMSATS Institute of Information Technology 96
  • 97. Kinds of Simple Association• w.r.t navigation• One-way Association• Two-way Association• w.r.t number of objects• Binary Association• Ternary Association• N-ary AssociationMay 25, 2013 COMSATS Institute of Information Technology 97
  • 98. One-way Association• We can navigate along a single direction only• Denoted by an arrow towards the server objectMay 25, 2013 COMSATS Institute of Information Technology 98
  • 99. Example – Association• Ali lives in a HouseMay 25, 2013 COMSATS Institute of Information Technology 99Ali Houselives-in11
  • 100. Example – Association• Ali drives his CarMay 25, 2013 COMSATS Institute of Information Technology 100Ali Cardrives*1
  • 101. Two-way Association• We can navigate in both directions• Denoted by a line between the associated objectsMay 25, 2013 COMSATS Institute of Information Technology 101
  • 102. Example – Two-way Association• Employee works for company• Company employs employeesMay 25, 2013 COMSATS Institute of Information Technology 102Employee Companyworks-for1*
  • 103. Example – Two-way Association• Yasir is a friend of Ali• Ali is a friend of YasirMay 25, 2013 COMSATS Institute of Information Technology 103Yasir Alifriend11
  • 104. Binary Association• Associates objects of exactly two classes• Denoted by a line, or an arrow between the associated objectsMay 25, 2013 COMSATS Institute of Information Technology 104
  • 105. Example – Binary Association• Association “works-for” associates objects of exactlytwo classesMay 25, 2013 COMSATS Institute of Information Technology 105Employee Companyworks-for1*
  • 106. Example – Binary Association• Association “drives” associates objects of exactly twoclassesMay 25, 2013 COMSATS Institute of Information Technology 106Ali Cardrives*1
  • 107. Ternary Association• Associates objects of exactly three classes• Denoted by a diamond with lines connected to associated objectsMay 25, 2013 COMSATS Institute of Information Technology 107
  • 108. Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Institute of Information Technology 108Student TeacherCourse1**
  • 109. Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Institute of Information Technology 109Project LanguagePerson*1*
  • 110. N-ary Association• An association between 3 or more classes• Practical examples are very rareMay 25, 2013 COMSATS Institute of Information Technology 110
  • 111. Composition• An object may be composed of other smaller objects• The relationship between the “part” objects and the “whole” objectis known as Composition• Composition is represented by a line with a filled-diamond headtowards the composer objectMay 25, 2013 COMSATS Institute of Information Technology 111
  • 112. Example – Composition of AliMay 25, 2013 COMSATS Institute of Information Technology 112AliBodyArmHeadLeg112 2
  • 113. Example – Composition of ChairMay 25, 2013 COMSATS Institute of Information Technology 113ChairSeatArmBackLeg112 4
  • 114. Composition is Stronger• Composition is a stronger relationship, because• Composed object becomes a part of the composer• Composed object can’t exist independentlyMay 25, 2013 COMSATS Institute of Information Technology 114
  • 115. Example – Composition is Stronger• Ali is made up of different body parts• They can’t exist independent of AliMay 25, 2013 COMSATS Institute of Information Technology 115
  • 116. Example – Composition is Stronger• Chair’s body is made up of different parts• They can’t exist independentlyMay 25, 2013 COMSATS Institute of Information Technology 116
  • 117. Aggregation• An object may contain a collection (aggregate) of other objects• The relationship between the container and the contained object iscalled aggregation• Aggregation is represented by a line with unfilled-diamond headtowards the containerMay 25, 2013 COMSATS Institute of Information Technology 117
  • 118. Example – AggregationMay 25, 2013 COMSATS Institute of Information Technology 118RoomCupboardBedChair Table*111
  • 119. Example – AggregationMay 25, 2013 COMSATS Institute of Information Technology 119Garden Plant*
  • 120. Aggregation is Weaker• Aggregation is weaker relationship, because• Aggregate object is not a part of the container• Aggregate object can exist independentlyMay 25, 2013 COMSATS Institute of Information Technology 120
  • 121. Example – Aggregation is Weaker• Furniture is not an intrinsic part of room• Furniture can be shifted to another room, and so can existindependent of a particular roomMay 25, 2013 COMSATS Institute of Information Technology 121
  • 122. Example – Aggregation is Weaker• A plant is not an intrinsic part of a garden• It can be planted in some other garden, and so can exist independentof a particular gardenMay 25, 2013 COMSATS Institute of Information Technology 122
  • 123. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May25,2013COMSATSInstituteofInformationTechnology123
  • 124. ThanksMay 25, 2013 COMSATS Institute of Information Technology 124
  • 125. CSC241:Object OrientedProgrammingSpring 20131. Inheritance Concepts2. PolymorphismMay 25, 2013 COMSATS Intitute of Information Technology125Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 126. Class diagram showinginheritanceMay 25, 2013 COMSATS Intitute of Information Technology 126Inheritance among classes isshown as open triangulararrowhead in UML ClassDiagram.Arrow be read as “derivedfrom”.
  • 127. Association• Objects in an object model interact with each other• Usually an object provides services to several other objects• An object keeps associations with other objects to delegate tasksMay 25, 2013 COMSATS Intitute of Information Technology 127
  • 128. Kinds of Association• Class Association• Inheritance• Object Association• Simple Association• Composition• AggregationMay 25, 2013 COMSATS Intitute of Information Technology 128
  • 129. Simple Association• Is the weakest link between objects• Is a reference by which one object can interact with some otherobject• Is simply called as “association”May 25, 2013 COMSATS Intitute of Information Technology 129
  • 130. Kinds of Simple Association• w.r.t navigation• One-way Association• Two-way Association• w.r.t number of objects• Binary Association• Ternary Association• N-ary AssociationMay 25, 2013 COMSATS Intitute of Information Technology 130
  • 131. One-way Association• We can navigate along a single direction only• Denoted by an arrow towards the server objectMay 25, 2013 COMSATS Intitute of Information Technology 131
  • 132. Example – Association• Ali lives in a HouseMay 25, 2013 COMSATS Intitute of Information Technology 132Ali Houselives-in11
  • 133. Example – Association• Ali drives his CarMay 25, 2013 COMSATS Intitute of Information Technology 133Ali Cardrives*1
  • 134. Two-way Association• We can navigate in both directions• Denoted by a line between the associated objectsMay 25, 2013 COMSATS Intitute of Information Technology 134
  • 135. Example – Two-way Association• Employee works for company• Company employs employeesMay 25, 2013 COMSATS Intitute of Information Technology 135Employee Companyworks-for1*
  • 136. Example – Two-way Association• Yasir is a friend of Ali• Ali is a friend of YasirMay 25, 2013 COMSATS Intitute of Information Technology 136Yasir Alifriend11
  • 137. Binary Association• Associates objects of exactly two classes• Denoted by a line, or an arrow between the associated objectsMay 25, 2013 COMSATS Intitute of Information Technology 137
  • 138. Example – Binary Association• Association “works-for” associates objects of exactlytwo classesMay 25, 2013 COMSATS Intitute of Information Technology 138Employee Companyworks-for1*
  • 139. Example – Binary Association• Association “drives” associates objects of exactly twoclassesMay 25, 2013 COMSATS Intitute of Information Technology 139Ali Cardrives*1
  • 140. Ternary Association• Associates objects of exactly three classes• Denoted by a diamond with lines connected to associated objectsMay 25, 2013 COMSATS Intitute of Information Technology 140
  • 141. Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Intitute of Information Technology 141Student TeacherCourse1**
  • 142. Example – Ternary Association• Objects of exactly three classes are associatedMay 25, 2013 COMSATS Intitute of Information Technology 142Project LanguagePerson*1*
  • 143. N-ary Association• An association between 3 or more classes• Practical examples are very rareMay 25, 2013 COMSATS Intitute of Information Technology 143
  • 144. Class diagram showingassociation• Association among classes is shown as a simple arrow (ray) in UML (UnifiedModeling Language) Class Diagram.• The direction of arrow shows ‘navigability’.• time12 calls time24.• This is unidirectional association.• If both classes call operation of the other, navigability is both sided (bidirectionalassociation).May 25, 2013 COMSATS Intitute of Information Technology 144
  • 145. Composition• An object may be composed of other smaller objects• The relationship between the “part” objects and the “whole” objectis known as Composition• Composition is represented by a line with a filled-diamond headtowards the composer objectMay 25, 2013 COMSATS Intitute of Information Technology 145
  • 146. Class diagram showingcompositionMay 25, 2013 COMSATS Intitute of Information Technology 146Composition among classes is shown as solid diamond arrowhead in UML ClassDiagram.
  • 147. Example – Composition of AliMay 25, 2013 COMSATS Intitute of Information Technology 147AliBodyArmHeadLeg112 2
  • 148. Example – Composition of ChairMay 25, 2013 COMSATS Intitute of Information Technology 148ChairSeatArmBackLeg112 4
  • 149. Composition is Stronger• Composition is a stronger relationship, because• Composed object becomes a part of the composer• Composed object can’t exist independentlyMay 25, 2013 COMSATS Intitute of Information Technology 149
  • 150. Example – Composition is Stronger• Ali is made up of different body parts• They can’t exist independent of AliMay 25, 2013 COMSATS Intitute of Information Technology 150
  • 151. Example – Composition is Stronger• Chair’s body is made up of different parts• They can’t exist independentlyMay 25, 2013 COMSATS Intitute of Information Technology 151
  • 152. Composition• Composition is a ‘consists of’ relationship.• COURSE_DATA consists of STUDENT_DATA (besides other things).• STUDENT_DATA lifetime is the same as COURSE_DATA.• Part may belong to only one whole.• The lifetime of the part is the same as the lifetime of the whole.May 25, 2013 National University of Computer and Emerging Sciences 152
  • 153. Aggregation• An object may contain a collection (aggregate) of other objects• The relationship between the container and the contained object iscalled aggregation• Aggregation is represented by a line with unfilled-diamond headtowards the containerMay 25, 2013 COMSATS Intitute of Information Technology 154
  • 154. Class diagram showingaggregationMay 25, 2013 COMSATS Intitute of Information Technology 155Aggregation among classes is shown as open diamond arrowhead in UML ClassDiagram.
  • 155. Example – AggregationMay 25, 2013 COMSATS Intitute of Information Technology 156RoomCupboardBedChair Table*111
  • 156. Example – AggregationMay 25, 2013 COMSATS Intitute of Information Technology 157Garden Plant*
  • 157. Aggregation is Weaker• Aggregation is weaker relationship, because• Aggregate object is not a part of the container• Aggregate object can exist independentlyMay 25, 2013 COMSATS Intitute of Information Technology 158
  • 158. Example – Aggregation is Weaker• Furniture is not an intrinsic part of room• Furniture can be shifted to another room, and so can existindependent of a particular roomMay 25, 2013 COMSATS Intitute of Information Technology 159
  • 159. Example – Aggregation is Weaker• A plant is not an intrinsic part of a garden• It can be planted in some other garden, and so can exist independentof a particular gardenMay 25, 2013 COMSATS Intitute of Information Technology 160
  • 160. More about „struct‟• More on data hiding• By default all the data members of struct areaccessible (through the struct variable/object)• This behaviour is known as data being ‘public’.• We can hide them by explicitly marking them as‘private’.• public: data or functions, can be accessed fromanywhere, outside or inside.• private: data or functions, cannot be accessed fromoutside.May 25, 2013 National University of Computer and Emerging Sciences 161
  • 161. More about „struct‟ …struct TEST{int x;}TEST var;var.x = 10;May 25, 2013 National University of Computer and Emerging Sciences 162struct TEST{public:int x;}TEST var;var.x = 10;struct TEST{private:int x;}TEST var;var.x = 10;//error
  • 162. More about „struct‟ …struct stack {int data[100];int top;} S;///////////////////////////////////void push(stack S, int a){assert(top<100);S.data[top]=a; S.top++;}May 25, 2013 COMSATS Intitute of Information Technology 163
  • 163. More about „struct‟ …struct TEST{private:int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}TEST var;var.Setx(10);int y = var.Getx();May 25, 2013 National University of Computer and Emerging Sciences 164struct TEST{private:int x;}TEST var;var.x = 10; //eint y = var.x; //eSo even legitimate access of data goes through an interface!We have secured the data further!!!
  • 164. Member functions definitionMay 25, 2013 National University of Computer and Emerging Sciences 165struct TEST {private:int x;public:void Setx(int val);int Getx();}void TEST::Setx(int val) {x = val;}int TEST::Getx() {return x;}main() {TEST var;var.Setx(10);int y = var.Getx();}• We can declare memberfunctions inside thestruct and define themoutside as well using thename of struct to resolveambiguity.• V. IMP: Note that thisallows us to separateheader andimplementation files!
  • 165. Class Compatibility• A class is behaviorally compatible with another if it supports all theoperations of the other class• Such a class is called subtype• A class can be replaced by its subtypeMay 25, 2013 COMSATS Intitute of Information Technology 166
  • 166. …Class Compatibility• Derived class is usually a subtype of the base class• It can handle all the legal messages (operations) of the base class• Therefore, base class can always be replaced by the derived classMay 25, 2013 COMSATS Intitute of Information Technology 167
  • 167. Example – Class CompatibilityMay 25, 2013 COMSATS Intitute of Information Technology 168ShapecolorverticesmovesetColordrawCircleradiusdrawcomputeAreaLinelengthdrawgetLengthTriangleangledrawcomputeArea
  • 168. Example – Class CompatibilityMay 25, 2013 COMSATS Intitute of Information Technology 169Filesize…openprint…ASCII File…print…PDF File…print…PS File…print…
  • 169. Polymorphism• In general, polymorphism refers to existence of different forms of asingle entity• For example, both Diamond and Coal are different forms of CarbonMay 25, 2013 COMSATS Intitute of Information Technology 170
  • 170. Polymorphism in OO Model• In OO model, polymorphism means that different objects can behavein different ways for the same message (stimulus)• Consequently, sender of a message does not need to know exact classof the receiverMay 25, 2013 COMSATS Intitute of Information Technology 171
  • 171. Example – PolymorphismMay 25, 2013 COMSATS Intitute of Information Technology 172ShapeLine Circle Triangledrawdrawdraw drawdrawView
  • 172. Example – PolymorphismMay 25, 2013 COMSATS Intitute of Information Technology 173FileASCII File PDF File PS Fileprintprintprint printprintEditor
  • 173. Polymorphism – Advantages• Messages can be interpreted in different waysdepending upon the receiver classMay 25, 2013 COMSATS Intitute of Information Technology 174ShapeLine Circle Triangledrawdrawdraw drawdrawView
  • 174. Polymorphism – Advantages• New classes can be added without changing the existingmodelMay 25, 2013 COMSATS Intitute of Information Technology 175SquaredrawShapeLine Circle Triangledrawdrawdraw drawdrawView
  • 175. Polymorphism – Advantages• In general, polymorphism is a powerful tool to develop flexible andreusable systemsMay 25, 2013 COMSATS Intitute of Information Technology 176
  • 176. Object-OrientedModelingAn ExampleMay 25, 2013 COMSATS Intitute of Information Technology 177
  • 177. Problem Statement• Develop a graphic editor that can draw different geometric shapessuch as line, circle and triangle. User can select, move or rotate ashape. To do so, editor provides user with a menu listing differentcommands. Individual shapes can be grouped together and canbehave as a single shape.May 25, 2013 COMSATS Intitute of Information Technology 178
  • 178. Identify ClassesExtract nouns in the problem statement• Develop a graphic editor that can draw different geometric shapessuch as line, circle and triangle. User can select, move or rotate ashape. To do so, editor provides user with a menu listing differentcommands. Individual shapes can be grouped together and canbehave as a single shape.May 25, 2013 COMSATS Intitute of Information Technology 179
  • 179. …Identify ClassesEliminate irrelevant classes• Editor – Very broad scope• User – Out of system boundaryMay 25, 2013 COMSATS Intitute of Information Technology 180
  • 180. …Identify ClassesAdd classes by analyzing requirements• Group – required to behave as a shape• “Individual shapes can be grouped together and can behave as a singleshape”• View – editor must have a display areaMay 25, 2013 COMSATS Intitute of Information Technology 181
  • 181. …Identify Classes• Shape• Line• Circle• Triangle• MenuMay 25, 2013 COMSATS Intitute of Information Technology 182• Group• ViewFollowing classes have been identified:
  • 182. Object Model – Graphic EditorMay 25, 2013 COMSATS Intitute of Information Technology 183LineCircleTriangleGroupShapeViewMenu
  • 183. Identify AssociationsExtract verbs connecting objects•“Individual shapes can be grouped together”• Group consists of lines, circles, triangles• Group can also consists of other groups(Composition)May 25, 2013 COMSATS Intitute of Information Technology 184
  • 184. … Identify AssociationsVerify access paths• View contains shapes• View contains lines• View contains circles• View contains triangles• View contains groups(Aggregation)May 25, 2013 COMSATS Intitute of Information Technology 185
  • 185. … Identify AssociationsVerify access paths• Menu sends message to View(Simple One-Way Association)May 25, 2013 COMSATS Intitute of Information Technology 186
  • 186. Object Model – Graphic EditorMay 25, 2013 COMSATS Intitute of Information Technology 187TriangleCircleLineShapeViewnnnnnnnnMenuGroupnnnnnnnnnn
  • 187. Identify AttributesExtract properties of the object• From the problem statement• Properties are not mentionedMay 25, 2013 COMSATS Intitute of Information Technology 188
  • 188. …Identify AttributesExtract properties of the object• From the domain knowledgeMay 25, 2013 COMSATS Intitute of Information Technology 189• Line– Color– Vertices– Length• Circle– Color– Vertices– Radius• Triangle– Color– Vertices– Angle• Shape– Color– Vertices
  • 189. …Identify AttributesExtract properties of the object• From the domain knowledgeMay 25, 2013 COMSATS Intitute of Information Technology 190• Group– noOfObjects• View– noOfObjects– selected• Menu– Name– isOpen
  • 190. Object Model – Graphic EditorMay 25, 2013 COMSATS Intitute of Information Technology 191MenunameisOpenViewnoOfObjectsselectedShapecolorverticesLinelengthCircleradiusGroupnoOfObjectsTriangleanglennnnnnnnnnnnnnnnn
  • 191. Identify OperationsExtract verbs connected with an objectMay 25, 2013 COMSATS Intitute of Information Technology 192• Develop a graphic editor that can drawdifferent geometric shapes such as line,circle and triangle. User can select, moveor rotate a shape. To do so, editor providesuser with a menu listing differentcommands. Individual shapes can begrouped together and can behave as asingle shape.
  • 192. … Identify OperationsEliminate irrelevant operations• Develop – out of system boundary• Behave – have broad semanticsMay 25, 2013 COMSATS Intitute of Information Technology 193
  • 193. …Identify OperationsFollowing are selected operations:May 25, 2013 COMSATS Intitute of Information Technology 194• Line– Draw– Select– Move– Rotate• Circle– Draw– Select– Move– Rotate
  • 194. …Identify OperationsFollowing are selected operations:May 25, 2013 COMSATS Intitute of Information Technology 195• Triangle– Draw– Select– Move– Rotate• Shape– Draw– Select– Move– Rotate
  • 195. …Identify OperationsFollowing are selected operations:May 25, 2013 COMSATS Intitute of Information Technology 196• Group– Draw– Select– Move– Rotate• Menu– Open– Select– Move– Rotate
  • 196. …Identify OperationsExtract operations using domain knowledgeMay 25, 2013 COMSATS Intitute of Information Technology 197• View– Add– Remove– Group– Show– Select– Move– Rotate
  • 197. GroupnoOfObjectsdraw()Triangleangledraw()nnCircleradiusdraw()nnLinelengthdraw()nnShapecolorverticesdraw()select()move()rotate()nnViewnoOfObjectsselectedadd()remove()group()show()select()move()rotate()nnnnnnnnMenunameisOpenopen()select()move()rotate()nMay 25, 2013 COMSATS Intitute of Information Technology 198
  • 198. Identify InheritanceSearch “is a kind of” by looking at keywords like “such as”, “forexample”, etc• “…shapes such as line, circle and triangle…”– Line, Circle and Triangle inherits from ShapeMay 25, 2013 COMSATS Intitute of Information Technology 199
  • 199. …Identify InheritanceBy analyzing requirements• “Individual shapes can be grouped together and can behave as asingle shape”• Group inherits from ShapeMay 25, 2013 COMSATS Intitute of Information Technology 200
  • 200. Refining the Object Model• Application of inheritance demands an iteration over the wholeobject model• In the inheritance hierarchy,• All attributes are shared• All associations are shared• Some operations are shared• Others are overriddenMay 25, 2013 COMSATS Intitute of Information Technology 201
  • 201. …Refining the Object ModelShare associations• View contains all kind of shapes• Group consists of all kind of shapesMay 25, 2013 COMSATS Intitute of Information Technology 202
  • 202. …Refining the Object ModelShare attributes• Shape – Line, Circle, Triangle and Group• Color, verticesMay 25, 2013 COMSATS Intitute of Information Technology 203
  • 203. …Refining the Object ModelShare operations• Shape – Line, Circle, Triangle and Group• Select• Move• RotateMay 25, 2013 COMSATS Intitute of Information Technology 204
  • 204. …Refining the Object ModelShare the interface and override implementation• Shape – Line, Circle, Triangle and Group• DrawMay 25, 2013 COMSATS Intitute of Information Technology 205
  • 205. Linelengthdraw()Circleradiusdraw()Triangleangledraw()GroupnoOfObjectsdraw()Shapecolorverticesdraw()select()move()rotate()nViewnoOfObjectsselectedadd()remove()group()show()select()move()rotate()nnMenunameisOpenopen()select()move()rotate()nMay 25, 2013 COMSATS Intitute of Information Technology 206
  • 206. GroupnoOfObjectsdraw()Triangleangledraw()nnCircleradiusdraw()nnLinelengthdraw()nnShapecolorverticesdraw()select()move()rotate()nnViewnoOfObjectsselectedadd()remove()group()show()select()move()rotate()nnnnnnnnMenunameisOpenopen()select()move()rotate()nMay 25, 2013 COMSATS Intitute of Information Technology 207
  • 207. Class• Class is a tool to realize objects• Class is a tool for defining a new typeMay 25, 2013 COMSATS Intitute of Information Technology 208
  • 208. Example• Lion is an object• Student is an object• Both has some attributes and some behaviorsMay 25, 2013 COMSATS Intitute of Information Technology 209
  • 209. Uses• The problem becomes easy to understand• Interactions can be easily modeledMay 25, 2013 COMSATS Intitute of Information Technology 210
  • 210. Type in C++• Mechanism for user defined types are• Structures• Classes• Built-in types are like int, float and double• User defined type can be• Student in student management system• Circle in a drawing softwareMay 25, 2013 COMSATS Intitute of Information Technology 211
  • 211. Abstraction• Only include details in the system that are required for making afunctional system• Student• Name• Address• Sibling• Father BusinessMay 25, 2013 COMSATS Intitute of Information Technology 212Relevant to our problemNot relevant to our problem
  • 212. Defining a New User Defined Typeclass ClassName{…DataType MemberVariable;ReturnType MemberFunction();…};May 25, 2013 COMSATS Intitute of Information Technology 213SyntaxSyntax
  • 213. Exampleclass Student{int rollNo;char *name;float CGPA;char *address;…void setName(char *newName);void setRollNo(int newRollNo);…};May 25, 2013 COMSATS Intitute of Information Technology 214Member variablesMemberFunctions
  • 214. Why Member Function• They model the behaviors of an object• Objects can make their data invisible• Object remains in consistent stateMay 25, 2013 COMSATS Intitute of Information Technology 215
  • 215. ExampleStudent aStudent;aStudent.rollNo = 514;aStudent.rollNo = -514; //ErrorMay 25, 2013 COMSATS Intitute of Information Technology 216
  • 216. Object and Class• Object is an instantiation of a user defined type or a classMay 25, 2013 COMSATS Intitute of Information Technology 217
  • 217. Declaring class variables• Variables of classes (objects) are declared just like variables ofstructures and built-in data typesTypeName VaraibaleName;int var;Student aStudent;May 25, 2013 COMSATS Intitute of Information Technology 218
  • 218. Accessing members• Members of an object can be accessed using• dot operator (.) to access via the variable name• arrow operator (->) to access via a pointer to an object• Member variables and member functions are accessed in a similarfashionMay 25, 2013 COMSATS Intitute of Information Technology 219
  • 219. Exampleclass Student{int rollNo;void setRollNo(intaNo);};Student aStudent;aStudent.rollNo;May 25, 2013 COMSATS Intitute of Information Technology 220Error
  • 220. struct -> class transition!class TEST {private:int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.Setx(10);int y = var.Getx();}May 25, 2013 National University of Computer and Emerging Sciences 221struct TEST {private:int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.Setx(10);int y = var.Getx();}• Replacing struct with class, does not have any affect!• This is the keyword that OOL (C++) provide for OOP!
  • 221. Diff. between struct & classclass TEST {int x;void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.x = 10; //errorvar.Setx(10); //errorint y = var.Getx(); //error}May 25, 2013 National University of Computer and Emerging Sciences 222struct TEST {int x;void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.x = 10; //possiblevar.Setx(10);int y = var.Getx();}• By default struct (C++) members are public,whereas class members are private.
  • 222. Diff. between struct & classclass TEST {int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.x = 10; //errorvar.Setx(10);int y = var.Getx();}May 25, 2013 National University of Computer and Emerging Sciences 223struct TEST {private:int x;public:void Setx(int val) { x = val; };int Getx() { return x; };}main() {TEST var;var.x = 10; //errorvar.Setx(10);int y = var.Getx();}• By default struct (C++) members are public,whereas class members are private.
  • 223. Access specifiersMay 25, 2013 COMSATS Intitute of Information Technology 224
  • 224. Access specifiers• There are three access specifiers• ‘public’ is used to tell that member can be accessed whenever you haveaccess to the object• ‘private’ is used to tell that member can only be accessed from a memberfunction• ‘protected’ to be discussed when we cover inheritanceMay 25, 2013 COMSATS Intitute of Information Technology 225
  • 225. Exampleclass Student{private:char * name;int rollNo;public:void setName(char *);void setRollNo(int);...};May 25, 2013 COMSATS Intitute of Information Technology 226Cannot be accessed outside classCan beaccessedoutside class
  • 226. Exampleclass Student{...int rollNo;public:void setRollNo(int aNo);};int main(){Student aStudent;aStudent.SetRollNo(1);}May 25, 2013 COMSATS Intitute of Information Technology 227
  • 227. Default access specifiers• When no access specifier is mentioned then by default the member isconsidered private memberMay 25, 2013 COMSATS Intitute of Information Technology 228
  • 228. Exampleclass Student{char * name;int RollNo;};class Student{private:char * name;int RollNo;};May 25, 2013 COMSATS Intitute of Information Technology 229
  • 229. Exampleclass Student{char * name;int RollNo;void SetName(char *);};Student aStudent;aStudent.SetName(Ali);May 25, 2013 COMSATS Intitute of Information Technology 230Error
  • 230. Exampleclass Student{char * name;int RollNo;public:void setName(char *);};Student aStudent;aStudent.SetName(“Ali”);May 25, 2013 COMSATS Intitute of Information Technology 231
  • 231. Unified Modeling Language (UML) class diagramMay 25, 2013 National University of Computer and Emerging Sciences 232 of 2110..*abstractstaticprivateassociation(“using”)inheritance(“is a”)
  • 232. Assignment (CP)• Install IBM Rational Rose or any other UML tool and draw thediagrams used in this lecture and take a print out of those diagrams toshow me what you have done.• Deadline: next classMay 25, 2013 COMSATS Intitute of Information Technology 233
  • 233. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 234
  • 234. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 235
  • 235. CSC241:Object OrientedProgrammingSpring 20131. Inheritance Concepts2. PolymorphismMay 25, 2013 COMSATS Intitute of Information Technology236Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 236. Review• Class• Concept• Definition• Data members• Member Functions• Access specifier
  • 237. Member Functions• Member functions are the functions that operate on the dataencapsulated in the class• Public member functions are the interface to the class
  • 238. Member Functions (contd.)• Define member function inside the class definitionOR• Define member function outside the class definition• But they must be declared inside class definition
  • 239. Function Inside Class Bodyclass ClassName {…public:ReturnType FunctionName() {…}};
  • 240. Example•Define a class of student that hasa roll number. This class shouldhave a function that can be usedto set the roll number
  • 241. Exampleclass Student{int rollNo;public:void setRollNo(int aRollNo){rollNo = aRollNo;}};
  • 242. Function Outside Class Bodyclass ClassName{…public:ReturnType FunctionName();};ReturnType ClassName::FunctionName(){…}Scoperesolutionoperator
  • 243. Exampleclass Student{…int rollNo;public:void setRollNo(int aRollNo);};void Student::setRollNo(int aRollNo){…rollNo = aRollNo;}
  • 244. Inline Functions• Instead of calling an inline function compiler replaces the code at thefunction call point• Keyword ‘inline’ is used to request compiler to make a function inline• It is a request and not a command
  • 245. Exampleinline int Area(int len, int hi){return len * hi;}int main(){cout << Area(10,20);}
  • 246. Inline Functions• If we define the function inside the class body then the function is bydefault an inline function• In case function is defined outside the class body then we must usethe keyword ‘inline’ to make a function inline
  • 247. Exampleclass Student{int rollNo;public:void setRollNo(int aRollNo){…rollNo = aRollNo;}};
  • 248. Exampleclass Student{…public:inline void setRollNo(int aRollNo);};void Student::setRollNo(int aRollNo){…rollNo = aRollNo;}
  • 249. Exampleclass Student{…public:void setRollNo(int aRollNo);};inline void Student::setRollNo(intaRollNo){…rollNo = aRollNo;}
  • 250. Exampleclass Student{…public:inline void setRollNo(int aRollNo);};inline void Student::setRollNo(intaRollNo){…rollNo = aRollNo;}
  • 251. Constructor
  • 252. Constructor• Constructor is used to initialize the objects of a class• Constructor is used to ensure that object is in well defined state atthe time of creation• Constructor is automatically called when the object is created• Constructor are not usually called explicitly
  • 253. Constructor (contd.)• Constructor is a special function having same name as the class name• Constructor does not have return type• Constructors are commonly public members
  • 254. Exampleclass Student{…public:Student(){rollNo = 0;…}};
  • 255. Exampleint main(){Student aStudent;/*constructor is implicitly called at thispoint*/}
  • 256. Default Constructor• Constructor without any argument is called default constructor• If we do not define a default constructor the compiler will generate adefault constructor• This compiler generated default constructor initialize the datamembers to their default values
  • 257. Exampleclass Student{int rollNo;char *name;float GPA;public:… //no constructors};
  • 258. ExampleCompiler generated default constructor{rollNo = 0;GPA = 0.0;name = NULL;}
  • 259. Constructor Overloading• Constructors can have parameters• These parameters are used to initialize the data members with usersupplied data
  • 260. Exampleclass Student{…public:Student();Student(char * aName);Student(char * aName, int aRollNo);Student(int aRollNo, int aRollNo, float aGPA);};
  • 261. ExampleStudent::Student(int aRollNo,char * aName){if(aRollNo < 0){rollNo = 0;}else {rollNo = aRollNo;}…}
  • 262. Exampleint main(){Student student1;Student student2(“Name”);Student student3(”Name”, 1);Student student4(”Name”,1,4.0);}
  • 263. Constructor Overloading• Use default parameter value to reduce the writing effort
  • 264. ExampleStudent::Student( char * aName = NULL,int aRollNo= 0,float aGPA = 0.0){…}Is equivalent toStudent();Student(char * aName);Student(char * aName, int aRollNo);Student(char * Name, int aRollNo, float aGPA);
  • 265. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 266
  • 266. How to correctly Search for asoftware @ google• When we need a software, the first place where wego is at Google Search. If you dont know thesoftware name, then we use some keywords atGoogle Search (for e.g. Note Taking software, VideoEditing software, Photo Editing software etc). OnceGoogle show us the results, we click the links afterreading its title and some description. Following suchpractice often wastes our time by clicking uselesslinks. What most of the people dont know is that,you can easily search for the software / applicationsat Google Search using its filtering options. Lets seehow we can do that• Consult the file uploadedMay 25, 2013 COMSATS Intitute of Information Technology 267
  • 267. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 268
  • 268. CSC241:Object OrientedProgrammingSpring 20131. FunctionsPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 269. Revision• Chapter 5 of bookMay 25, 2013 COMSATS Intitute of Information Technology 270
  • 270. FunctionsMay 25, 2013 COMSATS Intitute of Information Technology 271 A function groups a number of program statements into a unitand gives it a name. This unit can then be invoked from other parts of the program. The most important reason to use functions is to aid in theconceptual organization of a program Another reason to use functions is to reduce program size. Anysequence of instructions that appears in a program more thanonce is a candidate for being made into a function. The function’s code is stored in only one place in memory, eventhough the function is executed many times in the course of theprogram.
  • 271. Return typeInput argumentsMay 25, 2013 COMSATS Intitute of Information Technology 272
  • 272. FunctionsMay 25, 2013 COMSATS Intitute of Information Technology 273//demonstrates a simple function#include <iostream>using namespace std;int cube(int x); // function derationint main(){ // tests the cube() function:int n = 1;while (n != 0){cin >> n;cout << "tcube(" << n << ") = “<< cube(n) << endl; // Calling a function} // end of while loopsystem("PAUSE"); return 0;}//end of mainint cube( int x ){ // function definitionreturn x*x*x; // returns cube of x:} // { function body }Input ArgumentsReturn type
  • 273. FunctionsMay 25, 2013 COMSATS Intitute of Information Technology 274 Each integer read is passed to the cube() function by the call cube(n). The valuereturned by the function replaces the expression cube(n) and then is passed tothe output object cout The main() function passes the value 5 to the cube() function, and the cube()function returns the value 125 to the main() function. The argument n is passed by value to the formal parameter x. This simply meansthat x is assigned the value of n when the function is called.
  • 274. Default ArgumentsMay 25, 2013 COMSATS Intitute of Information Technology 275#include <iostream>using namespace std;//declaration with default argumentsvoid repchar(char=*, int=45);int main(){repchar(); //prints 45 asterisksrepchar(=); //prints 45 equal signsrepchar(+, 30); //prints 30 plus signssystem("PAUSE"); return 0;}// displays line of charactersvoid repchar(char ch, int n){// defaults supplied if necessaryfor(int j=0; j<n; j++) // loops n timescout << ch; // prints chcout << endl;}
  • 275. Inline FunctionMay 25, 2013 COMSATS Intitute of Information Technology 276 A function call involves substantial overhead.Extra time and space have to be used to invokethe function, pass parameters to it, allocatestorage for its local variables, store thecurrent variables and the location of executionin the main program, etc. In some cases, it is better to avoid all thisby specifying the function to be inline. Thistells the compiler to replace each call to thefunction with explicit code for the function. To the programmer, an inline function appearsthe same as an ordinary function, except forthe use of the inline specifier.
  • 276. Inline FunctionMay 25, 2013 COMSATS Intitute of Information Technology 277// demonstrates inline functions#include <iostream>using namespace std;inline float lbstokg(float pounds){// converts pounds to kilogramsreturn 0.453592 * pounds;}int main(){float lbs;cout << "nEnter your weight in pounds: ";cin >> lbs;cout << "Your weight in kilograms is " << lbstokg(lbs)<< endl;return 0;}
  • 277. RecursionMay 25, 2013 COMSATS Intitute of Information Technology 278 The existence of functions makes possible aprogramming technique called recursion. Recursion involves a function callingitself. This sounds rather improbable, andindeed a function calling itself is often abug. However, when used correctly thistechnique can be surprisingly powerful. Recursion is much easier to understand withan example than with lengthy explanations,so let‟s apply it to a program: The next program, uses recursion instead ofa loop to calculate factorial.
  • 278. RecursionMay 25, 2013 COMSATS Intitute of Information Technology 279#include <iostream>using namespace std;// calls itself to calculate factorialsunsigned long fct(unsigned long n){static int I = 0; I++;cout << "You Called Me " << I << " times" << endl;if(n > 1)return n * fct(n-1); //self callelsereturn 1;}int main(){int n;cout << "Enter an integer: "; cin >> n;cout << "Factorial of " << n << " is " << fct(n) << "n";system("PAUSE"); return 0;}
  • 279. RecursionMay 25, 2013 COMSATS Intitute of Information Technology 280
  • 280. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.May 25, 2013 COMSATS Intitute of Information Technology 281
  • 281. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 282
  • 282. CSC241:Object OrientedProgrammingSpring 20131. ConstructorsMay 25, 2013 COMSATS Intitute of Information Technology283Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 283. Constructor
  • 284. Constructor• Constructor is used to initialize the objects of a class• Constructor is used to ensure that object is in well defined state atthe time of creation (Lion 4 legs, Roll No +ve int)• Constructor is automatically called when the object is created• Constructor are not usually called explicitly
  • 285. Constructor (contd.)• Constructor is a special function having same name as the class name• Constructor does not have return type• Constructors are commonly public members
  • 286. Exampleclass Student{…public:Student(){rollNo = 0;…}};
  • 287. Exampleint main(){Student aStudent;/*constructor is implicitly called at thispoint*/}
  • 288. Default Constructor• Constructor without any argument is called default constructor• If we do not define a default constructor the compiler will generate adefault constructor• This compiler generated default constructor initialize the datamembers to their default values
  • 289. Exampleclass Student{int rollNo;char *name;float GPA;public:… //no constructors};
  • 290. ExampleCompiler generated default constructor{rollNo = 0;GPA = 0.0;name = NULL;}
  • 291. Constructor Overloading• Constructors can have parameters• These parameters are used to initialize the data members with usersupplied data
  • 292. Exampleclass Student{…public:Student();Student(char * aName);Student(char * aName, int aRollNo);Student(char * aName, int aRollNo, float aGPA);};
  • 293. ExampleStudent::Student(int aRollNo,char * aName){if(aRollNo < 0){rollNo = 0;}else {rollNo = aRollNo;}…}
  • 294. Exampleint main(){Student student1;Student student2(“Name”);Student student3(”Name”, 1);Student student4(”Name”,1,4.0);}
  • 295. Constructor Overloading• Use default parameter value to reduce the writing effort
  • 296. ExampleStudent::Student( char * aName = NULL,int aRollNo= 0,float aGPA = 0.0){…}Is equivalent toStudent();Student(char * aName);Student(char * aName, int aRollNo);Student(char * Name, int aRollNo, float aGPA);
  • 297. Copy Constructor• Copy constructor are used when:• Initializing an object at the time of creation• When an object is passed by value to a function
  • 298. Examplevoid func1(Student student){…}int main(){Student studentA;Student studentB = studentA;func1(studentA);}
  • 299. Copy Constructor (Syntax)Student::Student(const Student &obj){rollNo = obj.rollNo;name = obj.name;GPA = obj.GPA;}
  • 300. Shallow Copy• When we initialize one object with another then the compiler copiesstate of one object to the other• This kind of copying is called shallow copying
  • 301. ExampleStudent studentA;Student studentB = studentA;NameGPARollNostudentANameGPARollNostudentBAHMAD…Memory
  • 302. Assignment• Lab Assignment No 3May 25, 2013 COMSATS Intitute of Information Technology 303
  • 303. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 304
  • 304. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 305
  • 305. CSC241:Object OrientedProgrammingSpring 20131. DestructorPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 306. Review•Copy constructors•Destructor•this Pointer•Separation of interface andimplementation
  • 307. Destructor• You might guess that another function is calledautomatically when an object is destroyed. This is indeedthe case. Such a function is called a destructor.• A destructor also has the same name as the class namebut is preceded by a tilde (~) sign:• Like constructors, destructors do not have a return value.They also take no arguments.• The most common use of destructors is to de-allocatememory that was allocated for the object by theconstructor.May 25, 2013 COMSATS Intitute of Information Technology 308
  • 308. Using DestructorMay 25, 2013 COMSATS Intitute of Information Technology 309// foo.cpp demonstrates destructor#include <iostream>using namespace std;class Foo{private:int data;public:Foo() : data(0) // constructor (same name as class){cout<< "Wakeup n" ; }~Foo() // destructor (same name with tilde){cout<< "ByeBye n" ; }};int main(){Foo s1, s2; // define two objects of class Foosystem( "PAUSE" ); // Foo *s3; s3 = new Foo; delete s3;return 0;}
  • 309. this Pointer•There are situations wheredesigner wants to returnreference to current object from afunction•In such cases reference is takenfrom this pointer like (*this)
  • 310. ExampleStudent Student::setRollNo(int aNo){…return *this;}Student Student::setName(char *aName){…return *this;}
  • 311. Exampleint main(){Student aStudent;Student bStudent;bStudent = aStudent.setName(“Ahmad”);…bStudent = aStudent.setName(“Ali”).setRollNo(2);return 0;}
  • 312. Separation of interface andimplementation•Public member function exposed by aclass is called interface•Separation of implementation from theinterface is good software engineering
  • 313. Complex Number•There are two representations of complexnumber• Euler form• z = x + i y• Phasor form• z = |z| (cos  + i sin )• z is known as the complex modulus and  is known asthe complex argument or phase
  • 314. Examplefloat getX()float getY()void setNumber(float i, float j)…float xfloat yComplexOld implementationfloat getX()float getY()void setNumber(float i, float j)…float zfloat thetaComplexNew implementation
  • 315. Exampleclass Complex{ //oldfloat x;float y;public:void setNumber(float i, float j){x = i;y = j;}…};
  • 316. Exampleclass Complex{ //newfloat z;float theta;public:void setNumber(float i, float j){theta = arctan(j/i);…}…};
  • 317. Advantages•User is only concerned about ways of accessingdata (interface)•User has no concern about the internalrepresentation and implementation of the class
  • 318. Separation of interface andimplementation•Usually functions are defined in implementationfiles (.cpp) while the class definition is given inheader file (.h)•Some authors also consider this as separation ofinterface and implementation
  • 319. Student.hclass Student{int rollNo;public:void setRollNo(int aRollNo);int getRollNo();…};
  • 320. Student.cpp#include “student.h”void Student::setRollNo(int aNo){…}int Student::getRollNo(){…}
  • 321. Driver.cpp#include “student.h”int main(){Student aStudent;}
  • 322. Classes, Objects and Memory• you might have the impression that each object createdfrom a class contains separate copies of that class’s dataand member functions.• It’s true that each object has its own separate data items• But all the objects in a given class use the same memberfunctions.• The member functions are created and placed in memoryonly once—when they are defined in the class definition.• Since the functions for each object are identical. The dataitems, however, will hold different values.May 25, 2013 COMSATS Intitute of Information Technology 323
  • 323. May 25, 2013 COMSATS Intitute of Information Technology 324
  • 324. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 325
  • 325. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 326
  • 326. CSC241:Object OrientedProgrammingSpring 20131. Static class member2. Const member functionPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 327. static class member• What is a static variable? What is its scope (local, file)and storage class (automatic, static).• What if a data member is static?• A member variable defined as static has characteristicssimilar to a normal static variable: It is visible onlywithin the class, but its lifetime is the entire program.• It continues to exist even if there are no objects of theclass.• Why would we need a static member data?May 25, 2013 COMSATS Intitute of Information Technology 328
  • 328. static class member dataclass foo {private:static int count; //note: “declaration” only!public:foo() //incr count when object created{ count++;}int getcount() //returns count{ return count;}};int foo::count = 0; //*definition* of countMay 25, 2013 COMSATS Intitute of Information Technology 329int main(){foo f1, f2, f3; //create three objectscout << “count is “ << f1.getcount()<< endl; //each objectcout << “count is “ << f2.getcount()<< endl; //sees thecout << “count is “ << f3.getcount()<< endl; //same valuereturn 0;}
  • 329. static class member• For multiple objects of the same class, new memory isallocated for data members and shared memory for allthe functions.• This shared memory is also used for static datamembers.• Static data member requires two separate statementsfor:• Declaration (compiler is told about type and name)• Definition (compiler sets aside memory)May 25, 2013 COMSATS Intitute of Information Technology 330
  • 330. static class member• Why this two-part approach?• If static member data were defined inside the class (as itactually was in early versions of C++), it would violate theidea that a class definition is only a blueprint and does notset aside any memory.• Putting the definition of static member data outside theclass also serves to emphasize that the memory space forsuch data is allocated only once, before the program startsto execute,• and that one static member variable is accessed by anentire class; each object does not have its own version ofthe variable, as it would with ordinary member data.• In this way a static member variable is more like a globalvariable.May 25, 2013 COMSATS Intitute of Information Technology 331
  • 331. static class member• Be careful:• It’s easy to handle static data incorrectly, and the compiler isnot helpful about such errors.• If you include the declaration of a static variable but forget itsdefinition, there will be no warning from the compiler.• Everything looks fine until you get to the linker, which will tellyou that you’re trying to reference an undeclared globalvariable.• This happens even if you include the definition but forget theclass name (the foo:: in the example above).May 25, 2013 COMSATS Intitute of Information Technology 332
  • 332. Variable packing in memory• If you do a ‘sizeof(class_obj_or_name)’ for an object ofa class/struct or class/struct name, you get the size ofthe memory allocated for data members.• Memory alignment in class/struct is a bit different.May 25, 2013 COMSATS Intitute of Information Technology 333
  • 333. Data member packing inclass/structclass Counter{private:unsigned char count;unsigned char temp2;short temp1;int temp;static int obj;public:Counter() : count(0){}}May 25, 2013 COMSATS Intitute of Information Technology 334int sz = sizeof(Counter);ORCounter c1;int sz = sizeof(c1);Gives sz = 8If there was no temp2, sz will still be 8.If there was no temp1, sz will still be 8.If rearranged, sz will change.Experiment at home and make concepts.
  • 334. const Member Functions•There are functions that are meant to beread only•There must exist a mechanism to detecterror if such functions accidentally changethe data memberMay 25, 2013 COMSATS Intitute of Information Technology 335
  • 335. Examplebool Student::isRollNo(int aNo){if(rollNo = = aNo){return true;}return false;}May 25, 2013 COMSATS Intitute of Information Technology 336
  • 336. Examplebool Student::isRollNo(int aNo){/*undetected typing mistake*/if(rollNo = aNo){return true;}return false;}May 25, 2013 COMSATS Intitute of Information Technology 337
  • 337. Examplebool Student::isRollNo(int aNo)const{/*compiler error*/if(rollNo = aNo){return true;}return false;}May 25, 2013 COMSATS Intitute of Information Technology 338
  • 338. const Member Functions•Keyword const is placed at the end of theparameter listMay 25, 2013 COMSATS Intitute of Information Technology 339
  • 339. const Member FunctionsDeclaration:class ClassName{ReturnVal Function() const;};Definition:ReturnVal ClassName::Function() const{…}May 25, 2013 COMSATS Intitute of Information Technology 340
  • 340. Exampleclass Student{public:int getRollNo() const {return rollNo;}};May 25, 2013 COMSATS Intitute of Information Technology 341
  • 341. const Functions•Constant member functions cannot modify thestate of any object•They are just “read-only”•Errors due to typing are also caught at compiletimeMay 25, 2013 COMSATS Intitute of Information Technology 342
  • 342. const Functions•Constructors and Destructors cannot be const•Constructor and destructor are used to modifythe object to a well defined stateMay 25, 2013 COMSATS Intitute of Information Technology 343
  • 343. Exampleclass Time{public:Time() const {} //error…~Time() const {} //error…};May 25, 2013 COMSATS Intitute of Information Technology 344
  • 344. const Function•Constant member function cannot changedata member•Constant member function cannot accessnon-constant member functionsMay 25, 2013 COMSATS Intitute of Information Technology 345
  • 345. Exampleclass Student{char * name;public:char *getName();void setName(char * aName);int ConstFunc() const{name = getName();//errorsetName(“Ahmad”);//error}};May 25, 2013 COMSATS Intitute of Information Technology 346
  • 346. May 25, 2013 COMSATS Intitute of Information Technology 347
  • 347. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 348
  • 348. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 349
  • 349. CSC241:Object OrientedProgrammingSpring 20131. Arrays & String (Chapter7)Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 350. Arrays In everyday life we commonly group similarobjects into units. We buy eggs by the carton. In computer languages we also need to grouptogether data items of the same type. The mostbasic mechanism that accomplishes this in C++is the array. Arrays can hold a few data items or tens ofthousands. The data items grouped in an arraycan be simple types such as int or float, orthey can be user-defined types such asstructures and objects. An array groups items of the same type. Theitems in a in an array are accessed by anindex number. Using an index number to specifyan item allows easy access to a large numberof items.
  • 351. Defining, Reading and Writing Array// gets four ages from user, displays them#include <iostream>using namespace std;int main(){int age[4], j; //array age of 4 intsfor(j=0; j<4; j++){ //get 4 agescout << "Enter an age: ";cin >> age[j]; //access array element}for(j=0; j<4; j++){ //display 4 agescout << "age[" << j << "] = " << age[j] << endl;cout <<"Address " << &age[j] << " = " << age[j] <<endl;}system("PAUSE"); return 0;}
  • 352. Calculating Average#include <iostream>using namespace std;int main(){double avg, sum = 0 ;int i ; int marks[10] ; /* array declaration */for ( i = 0 ; i <= 9 ; i++ ){cout << "nEnter marks ";cin >> marks[i]; /* store data in array */}for ( i = 0 ; i <= 9 ; i++ )sum = sum + marks[i] ; /* read data fromarray*/avg = sum / 10 ;cout << "n Average marks = " << avg <<endl;system("PAUSE"); return 0;}
  • 353. Using Direct Access on an Array// Using Direct Access on Array#include <iostream>using namespace std;int main(){int mem[]={50,60,70} ; // Initialize the arraycout << "mem[0] = " << mem[0] << endl;cout << "mem[1] = " << mem[1] << endl;cout << "mem[2] = " << mem[2] << endl;mem[0] = 80;mem[1] = 90;mem[2] = 100;cout << endl;cout << "mem[0] = " << mem[0] << endl;cout << "mem[1] = " << mem[1] << endl;cout << "mem[2] = " << mem[2] << endl;system("PAUSE"); return 0;}
  • 354. Printing in Reverse Order#include <iostream>using namespace std;int main(){const int SIZE=5; // defines the size N for 5 elementsdouble a[SIZE]; // declares the array‟s elements astype doublecout << "Enter " << SIZE << " numbers:t";for (int i=0; i<SIZE; i++)cin >> a[i];cout << "In reverse order: ";for (int i=SIZE-1; i>=0; i--)cout << " " << a[i];system("PAUSE"); return 0;}
  • 355. Out of Bounds#include <iostream>using namespace std;int main(){float a[] = { 22.2,44.4, 66.6 };float x=11.1;cout << "I m going to Crash " << endl;cin >> x;a[3333] = 88.8; // ERROR: index is out of bounds!return 0;}
  • 356. Passing Array to Function#include <iostream>using namespace std;int sum(int[],int); // declarationint main(){int a[] = { 11,33, 55,77 };int size = sizeof(a)/sizeof(int);cout << "sum(a,size) = " << sum(a,size) << endl;cout << endl << a[0] << endl;system("PAUSE"); return 0;}int sum(int a[],int n){int sum=0;for (int i=0; i<n; i++)sum += a[i];a[0] = 100;return sum;}
  • 357. n Dimensional Arrays#include <iostream>using namespace std;int main(){ const int row=2, col=3; int i,j;int ary[row][col] = {{11,12,13},{21,22,23}};for(i=0 ; i< row ; i++){for(j=0 ; j<col; j++){ cout << ary[i][j] << " ";}cout << endl;}for(i=0 ; i< row ; i++){for(j=0 ; j<col; j++){cout << &ary[i][j] << "="<<ary[i][j]<<"t";}cout << endl;}return 0;}
  • 358. n Dimensional Arrays0x22ff40 = 110x22ff44 = 120x22ff48 = 130x22ff4C = 210x22ff50 = 220x22ff54 = 23ary[0][0]=ary[0][1]=ary[0][2]=ary[1][0]=ary[1][1]=ary[1][2]=232221131211
  • 359. 2-Dimensional Arrays#include <iostream>using namespace std;int main(){ const int row=3, col=3; int i,j;int ary[row][col] = {{11,12,13},{21,22,23},{31,32,33} };for(i=0 ; i< row ; i++){for(j=0 ; j<col; j++){ cout << ary[i][j] << " ";}cout << endl;}for(i=0 ; i< row ; i++){for(j=0 ; j<col; j++){cout << &ary[i][j] << "="<<ary[i][j]<<"t";}cout << endl;}system("PAUSE"); return 0;}
  • 360. 3-Dimensional Arrays0x22ff30 = 110x22ff34 = 120x22ff38 = 130x22ff3C = 210x22ff40 = 220x22ff44 = 23ary[0][0]=ary[0][1]=ary[0][2]=ary[1][0]=ary[1][1]=ary[1][2]=0x22ff48 = 310x22ff4C = 320x22ff50 = 33ary[2][0]=ary[2][1]=ary[2][2]=333231232221131211
  • 361. Calculating Square of a Matrix#include <iostream>using namespace std;int main(){ const int row=3, col=3; int i,j;int A[row][col];cout << "Square of a " <<row <<"x"<<col<<"Matrices"<<endl;for(i=0 ; i< row ; i++){for(j=0 ; j<col; j++){cout << "A[" << i+1 << "][" << j+1 << "]= ";cin >> A[i][j];}}for(i=0 ; i< row ; i++)for(j=0 ; j<col; j++)A[i][j] = A[i][j]*A[i][j];for(i=0 ; i< row ; i++){for(j=0 ; j<col; j++)cout << A[i][j] << "t";cout << endl;}return 0;}
  • 362. Passing 2D Array to Function#include <iostream>using namespace std;void get_data(float a[][3],int row, int col){int i,j;for (i=0; i<row; i++)for (j=0; j<col; j++){cout << "A["<<i+1<<"]["<<j+1<<"]:";cin >> a[i][j];}}void show_data(float a[][3],int row, int col){int i,j;for (i=0; i<row; i++){for (j=0; j<col; j++){cout << a[i][j] << "t";}cout << endl; }}int main(){float matrix[4][3]; // 4 rows and 3 columnsget_data(matrix,4,3);show_data(matrix,4,3);return 0;}
  • 363. Passing 3D Array to Function (1/2)#include <iostream>using namespace std;void get_data(float a[][3][2],int row, int col,int page){int i,j,k;for (k=0; k<page; k++){for (i=0; i<row; i++){for (j=0; j<col; j++){cout <<"A["<< i <<"]["<< j <<"]["<< k <<"]:";cin >> a[i][j][k];} // end of for (j=0} // end of for (i=0} // end of for (k=0}
  • 364. Passing 3D Array to Function (2/2)void show_data(float a[][3][2],int row, int col, int page){int i,j,k;for (k=0; k<page; k++){for (i=0; i<row; i++){for (j=0; j<col; j++){cout << a[i][j][k] << "t";}cout << endl;}cout << endl;}}int main(){float matrix[4][3][2]; // 4 rows, 3 columns, 2 pagesget_data(matrix,4,3,2);show_data(matrix,4,3,2);system("PAUSE");return 0;}
  • 365. Sorting Data Using Bubble Sort Algo#include <iostream>using namespace std;void print( float[], int );void sort ( float[], int );int main(){int i; float data[10];cout << "Enter 10 Numbers for Sorting n";for( i=0 ; i<10 ; i++ ){cout << "Enter No." <<i+1<< ":" ;cin >> data[i];}sort(data,10);print(data,10);return 0;}
  • 366. Sorting Data Using Bubble Sort Algovoid sort( float a[], int n ){ // bubble sort:for (int i=1; i<n; i++) // bubble up max{a[0..n-i]}:for (int j=0; j<n-i; j++)if (a[j] > a[j+1]){float temp = a[j];a[j]=a[j+1];a[j+1] = temp;}}void print( float a[], int n ){cout << " Sorted Data is " << endl;for (int i=0; i<n; i++)cout << a[i] <<" ";}
  • 367. Using C-string#include <iostream>#include <iomanip.h>using namespace std;int main(){char str[] = { M,., ,A,l,i,0, ,I,I,U,0}; // char ch [] = "M. Ali";int size = sizeof(str);cout << "n The Character Array Size is :" <<size<< " Bytes" << endl;for ( int i=0 ; i<size ; i++ )cout << "str[" << i << "]=" <<str[i] <<" =["<< int(str[i]) << "]" << endl;cout << endl << str << endl;system("PAUSE");return 0;}
  • 368. Reading Embedded Blanks// blanksin.cpp reads string with embedded blanks#include <iostream>using namespace std;int main(){const int MAX = 80; // max characters in stringchar str[MAX]; // string variable strcout << "nEnter a string: ";// cin.get() means a member function get() of the stream// class of which cin is an objectcin.get(str, MAX); // put string in str// first argument to get() is the array address wherethe// string being input will be placed.// The second argument specifies the maximum size of the// arraycout << "You entered: " << str << endl;return 0;}
  • 369. Copying a String the Hard Way// strcopy1.cpp// copies a string using a for loop#include <iostream>#include <cstring> //for strlen()using namespace std;int main(){ //initialized stringchar str1[] = "Oh, Captain, my Captain! ""our fearful trip is done";const int MAX = 80; int j; // MAX is size of str2 bufferchar str2[MAX]; //empty stringfor( j=0; j<strlen(str1); j++) //copy strlen charactersstr2[j] = str1[j]; // from str1 to str2str2[j] = 0; //insert NULL at endcout << str2 << endl; //display str2system("PAUSE"); return 0;}
  • 370. Copying a String the Easy Way// strcopy2.cpp// copies a string using strcpy() function#include <iostream>#include <cstring> //for strcpy()using namespace std;int main(){char str1[] = "Tiger, tiger, burning brightn""In the forests of the night";const int MAX = 80; //size of str2 bufferchar str2[MAX]; //empty stringstrcpy(str2, str1); //copy str1 to str2cout << str2 << endl; //display str2system("PAUSE"); return 0;}
  • 371. Array of Strings// straray.cpp// array of strings#include <iostream>using namespace std;int main(){const int DAYS = 7; //number of strings in arrayconst int MAX = 10; //maximum size of each string//An array of stringschar star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday","Wednesday", "Thursday", "Friday" , "Saturday" };for( int j=0 ; j<DAYS ; j++) //display every stringcout << star[j] << endl;system("PAUSE");return 0;}
  • 372. Array of Strings
  • 373. Lab TaskWrite a and test a program to calculate Determinant and Reverse of a 3x3 matrix
  • 374. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 376
  • 375. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 377
  • 376. CSC241:Object OrientedProgrammingSpring 20131. Composition2. Aggregation3. Friend FunctionsPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 377. Pointer to Objects• Pointer to objects are similar as pointer to built-in types• They can also be used to dynamically allocate objects
  • 378. Exampleclass Student{…public:Studen();Student(char * aName);void setRollNo(int aNo);};
  • 379. Example (Aggregation)int main(){Student obj;Student *ptr;ptr = &obj;ptr->setRollNo(10);return 0;}
  • 380. Allocation with new Operator• new operator can be used to create objects at runtime
  • 381. Exampleint main(){Student *ptr;ptr = new Student;ptr->setRollNo(10);return 0;}
  • 382. Exampleint main(){Student *ptr;ptr = new Student(“Ali”);ptr->setRollNo(10);return 0;}
  • 383. Breakup of new Operation• new operator is decomposed as follows• Allocating space in memory• Calling the appropriate constructor
  • 384. Case StudyDesign a class date through which user must be able to performfollowing operations• Get and set current day, month and year• Increment by x number of days, months and year• Set default date
  • 385. Attributes• Attributes that can be seen in this problem statement are• Day• Month• Year• Default date
  • 386. Attributes• The default date is a feature shared by all objects• This attribute must be declared a static member
  • 387. Attributes in Date.hclass Date{int day;int month;int year;static Date defaultDate;…};
  • 388. Interfaces• getDay• getMonth• getYear• setDay• setMonth• setYear• addDay• addMonth• addYear• setDefaultDate
  • 389. Interfaces• As the default date is a static member the interface setDefaultDateshould also be declared static
  • 390. Interfaces in Date.hclass Date{…public:void setDay(int aDay);int getDay() const;void addDay(int x);……};
  • 391. Interfaces in Date.hclass Date{…public:static void setDefaultDate(int aDay,int aMonth, int aYear);…};
  • 392. Constructors and Destructors in Date.hDate(int aDay = 0,int aMonth= 0, int aYear= 0);~Date(); //Destructor};
  • 393. Implementation of Date Class• The static member variables must be initializedDate Date::defaultDate (07,3,2013);
  • 394. ConstructorsDate::Date(int aDay, int aMonth,int aYear) {if(aDay==0) {this->day = defaultDate.day;}else{setDay(aDay);}//similarly for other members}
  • 395. Destructor• We are not required to do any house keeping chores in destructorDate::~Date{}
  • 396. Getter and Settervoid Date::setMonth(int a){if(a > 0 && a <= 12){month = a;}int getMonth() const{return month;}
  • 397. addYearvoid Date::addYear(int x){year += x;if(day == 29 && month == 2&& !leapyear(year)){day = 1;month = 3;}}
  • 398. Helper Functionclass Date{…private:bool leapYear(int x) const;…};
  • 399. Helper Functionbool Date::leapYear(int x) const{if((x%4 == 0 && x%100 != 0)|| (x%400==0)){return true;}return false;}
  • 400. setDefaultDatevoid Date::setDefaultDate(int d, int m, int y){if(d >= 0 && d <= 31){day = d;}…}
  • 401. AggregationComposition vs. Aggregation►Aggregation is a weak relationshipRoom(char *, int)~Room()FoldChair(int) : bool…Chair()DoSomething() : voidFoldChair() : boolUnFoldChair() : bool~Chair()…area : floatchairs[50]:Chair *Room…Chair
  • 402. Aggregation►In aggregation, a pointer or reference to an object iscreated inside a class►The sub-object has a life that is NOTdependanton the life of its master class►e.g:Chairs can be moved inside or outside at anytimeWhen Room is destroyed, the chairs may or maynot be destroyed
  • 403. Aggregationclass Room{private:float area;Chair * chairs[50];Public:Room();void AddChair(Chair *, int chairNo);Chair * GetChair(int chairNo);bool FoldChair(int chairNo);…};
  • 404. AggregationRoom::Room(){for(int i = 0; i < 50; i++)chairs[i] = NULL;}void Room::AddChair(Chair *chair1, int chairNo){if(chairNo >= 0 && chairNo < 50)chairs[chairNo] = chair1;}
  • 405. AggregationChair * Room::GetChair(int chairNo){if(chairNo >= 0 && chairNo < 50)return chairs[chairNo];elsereturn NULL;}bool Room::FoldChair(int chairNo){if(chairNo >= 0 && chairNo < 50)return chairs[chairNo]->FoldChair();elsereturn false;}
  • 406. Aggregationint main(){Chair ch1;{Room r1;r1.AddChair(&ch1, 1);r1.FoldChair(1);}ch1.UnFoldChair(1);return 0;}
  • 407. Friend Functions►Consider the following class:class X{private:int a, b;public:void MemberFunction();…}
  • 408. Friend Functions►Global function:void DoSomething(X obj){obj.a = 3; //Errorobj.b = 4; //Error}
  • 409. Friend Functions►In order to access the member variables of the class, functiondefinition must be made a friend function:class X{private:int a, b;public:…friend void DoSomething(X obj);}►Now the function DoSomething can access data membersof class X
  • 410. Friend Functions►Prototypes of friend functionsappear in the class definition►But friend functions are NOTmember functions
  • 411. Friend Functions►Friend functions can be placed anywhere in the classwithout any effect►Access specifiers don’t affect friend functions orclassesclass X{...private:friend void DoSomething(X);public:friend void DoAnything(X);...};
  • 412. Friend Functions►While the definition of the friend function is:void DoSomething(X obj){obj.a = 3; // No Errorobj.b = 4; // No Error…}►friend keyword is not given in definition
  • 413. Friend Functions►If keyword friend is used in the functiondefinition, it’s a syntax error//Error…friend void DoSomething(X obj){…}
  • 414. Friend Classes•Similarly, one class can also be made friend ofanother class:class X{friend class Y;…};•Member functions of class Y can accessprivate data members of class X
  • 415. Friend Classes•Example:class X{friend class Y;private:int x_var1, x_var2;...};
  • 416. Friend Classesclass Y{private:int y_var1, y_var2;X objX;public:void setX(){objX.x_var1 = 1;}};
  • 417. Friend Classesint main(){Y objY;objY.setX();return 0;}
  • 418. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 420
  • 419. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 421
  • 420. CSC241:Object OrientedProgrammingSpring 20131. Operator OverloadingMay25,2013COMSATSIntituteofInformationTechnology422Please turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 421. Operator overloading►Consider the following class:class Complex{private:double real, img;public:Complex Add(const Complex &);Complex Subtract(const Complex &);Complex Multiply(const Complex &);…}May25,2013COMSATSIntituteofInformationTechnology423
  • 422. Operator overloading►Function implementation:Complex Complex::Add(const Complex & c1){Complex t;t.real = real + c1.real;t.img = img + c1.img;return t;}May25,2013COMSATSIntituteofInformationTechnology424
  • 423. Operator overloading►The following statement:Complex c3 = c1.Add(c2);Adds the contents of c2 to c1 and assignsit to c3 (copy constructor)May25,2013COMSATSIntituteofInformationTechnology425
  • 424. Operator overloading►To perform operations in a singlemathematical statement e.g:c1+c2+c3+c4►We have to explicitly write:►c1.Add(c2.Add(c3.Add(c4)))May25,2013COMSATSIntituteofInformationTechnology426
  • 425. Operator overloading►Alternative way is:► t1 = c3.Add(c4);► t2 = c2.Add(t1);► t3 = c1.Add(t2);May25,2013COMSATSIntituteofInformationTechnology427
  • 426. Operator overloading►If the mathematical expression is big:• Converting it to C++ code will involvecomplicated mixture of function calls• Less readable• Chances of human mistakes are very high• Code produced is very hard to maintainMay25,2013COMSATSIntituteofInformationTechnology428
  • 427. Operator overloading►C++ provides a very elegant solution:►“Operator overloading”►C++ allows you to overload common operators like +,- or * etc…►Mathematical statements don’t have to be explicitlyconverted into function callsMay25,2013COMSATSIntituteofInformationTechnology429
  • 428. Operator overloading►Assume that operator + has beenoverloaded►Actual C++ code becomes:c1+c2+c3+c4►The resultant code is very easy to read,write and maintainMay25,2013COMSATSIntituteofInformationTechnology430
  • 429. Operator overloading►C++ automatically overloads operators forpre-defined types►Example of predefined types:intfloatdoublecharlongMay25,2013COMSATSIntituteofInformationTechnology431
  • 430. Operator overloading►Example:float x;int y;x = 102.02 + 0.09;Y = 50 + 47;May25,2013COMSATSIntituteofInformationTechnology432
  • 431. Operator overloading►The compiler probably calls the correctoverloaded low level function for addition i.e:// for integer addition:Add(int a, int b)// for float addition:Add(float a, float b)May25,2013COMSATSIntituteofInformationTechnology433
  • 432. Operator overloading►Operator functions are not usually calleddirectly►They are automatically invoked to evaluatethe operations they implementMay25,2013COMSATSIntituteofInformationTechnology434
  • 433. Operator overloading►List of operators that can beoverloaded in C++:May25,2013COMSATSIntituteofInformationTechnology435
  • 434. Operator overloading►List of operators that can’t beoverloaded:►Reason: They take name, rather thanvalue in their argument except for ?:►?: is the only ternary operator in C++and can’t be overloadedMay25,2013COMSATSIntituteofInformationTechnology436
  • 435. Operator overloading►The precedence of an operator is NOTaffected due to overloading►Example:c1*c2+c3c3+c2*c1both yield the same answerMay25,2013COMSATSIntituteofInformationTechnology437
  • 436. Operator overloading►Associativity is NOT changeddue to overloading►Following arithmeticexpression always is evaluatedfrom left to right:c1 + c2 + c3 + c4May25,2013COMSATSIntituteofInformationTechnology438
  • 437. Operator overloading►Unary operators and assignmentoperator are right associative, e.g:a=b=c is same as a=(b=c)►All other operators are leftassociative:c1+c2+c3 is same as(c1+c2)+c3May25,2013COMSATSIntituteofInformationTechnology439
  • 438. Operator overloading►Always write code representingthe operator►Example:Adding subtraction codeinside the + operatorwill create chaosMay25,2013COMSATSIntituteofInformationTechnology440
  • 439. Operator overloading►Creating a new operator is asyntax error (whether unary, binaryor ternary)► You cannot create $May25,2013COMSATSIntituteofInformationTechnology441
  • 440. Operator overloading►Arity of an operator is NOT affected byoverloading►Example:Division operator will takeexactly two operands in anycase:b = c / dMay25,2013COMSATSIntituteofInformationTechnology442
  • 441. Binary operators►Binary operators act on two quantities►Binary operators:May25,2013COMSATSIntituteofInformationTechnology443
  • 442. Binary operators►General syntax:Member function:TYPE1 CLASS::operator B_OP(TYPE2 rhs){...}May25,2013COMSATSIntituteofInformationTechnology444
  • 443. Binary operators►General syntax:Non-member function:TYPE1 operator B_OP(TYPE2 lhs,TYPE3 rhs){...}May25,2013COMSATSIntituteofInformationTechnology445
  • 444. Binary operators►The “operator OP” must have at leastone formal parameter of type class (userdefined type)►Following is an error:int operator + (int, int);May25,2013COMSATSIntituteofInformationTechnology446
  • 445. Binary operators►Overloading + operator:class Complex{private:double real, img;public:…Complex operator +(constComplex & rhs);};May25,2013COMSATSIntituteofInformationTechnology447
  • 446. Binary operatorsComplex Complex::operator +(const Complex & rhs){Complex t;t.real = real + rhs.real;t.img = img + rhs.img;return t;}May25,2013COMSATSIntituteofInformationTechnology448
  • 447. Binary operators►The return type is Complex so as to facilitate complexstatements like:Complex t = c1 + c2 + c3;►The above statement is automatically converted bythe compiler into appropriate function calls:(c1.operator +(c2)).operator +(c3);May25,2013COMSATSIntituteofInformationTechnology449
  • 448. Binary operators►If the return type was void,class Complex{...► public:► void operator+(► const Complex & rhs);};May25,2013COMSATSIntituteofInformationTechnology450
  • 449. Binary operatorsvoid Complex::operator+(constComplex & rhs){real = real + rhs.real;img = img + rhs.img;};May25,2013COMSATSIntituteofInformationTechnology451
  • 450. Binary operators►we have to do the same operation c1+c2+c3 as:c1+c2c1+c3// final result is stored in c1May25,2013COMSATSIntituteofInformationTechnology452
  • 451. Binary operators►Drawback of void return type:Assignments and cascaded expressions are not possibleCode is less readableDebugging is toughCode is very hard to maintainMay25,2013COMSATSIntituteofInformationTechnology453
  • 452. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 454
  • 453. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 455
  • 454. CSC241:Object OrientedProgrammingSpring 20131. InheritancePlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 455. Inheritance in Classes• If a class B inherits from class A, then B contains allthe characteristics (information structure andbehavior) of class A• The parent class is called base class and the child classis called derived class• Besides inherited characteristics, derived class mayhave its own unique characteristicsMay 25, 2013 COMSATS Intitute of Information Technology 457
  • 456. UML NotationMay 25, 2013 COMSATS Intitute of Information Technology 458Parent ClassChild ClassBase ClassDerived Class
  • 457. Inheritance in C++• There are three types of inheritance in C++• Public• Private• ProtectedMay 25, 2013 COMSATS Intitute of Information Technology 459
  • 458. “IS A” Relationship• IS A relationship is modeled with the help of publicinheritance• Syntaxclass ChildClass: public BaseClass{...};May 25, 2013 COMSATS Intitute of Information Technology 460
  • 459. Exampleclass Person{...};class Student: public Person{...};May 25, 2013 COMSATS Intitute of Information Technology 461
  • 460. Accessing Members• Public members of base class become public memberof derived class• Private members of base class are not accessible fromoutside of base class, even in the derived class(Information Hiding)May 25, 2013 COMSATS Intitute of Information Technology 462
  • 461. Exampleclass Person{char *name;int age;...public:const char *GetName() const;int GetAge() const;...};May 25, 2013 COMSATS Intitute of Information Technology 463
  • 462. Exampleclass Student: public Person{int semester;int rollNo;...public:int GetSemester() const;int GetRollNo() const;void Print() const;...};May 25, 2013 COMSATS Intitute of Information Technology 464
  • 463. Examplevoid Student::Print(){cout << name << “ is in” << “ semester” << semester;}May 25, 2013 COMSATS Intitute of Information Technology 465ERROR
  • 464. Examplevoid Student::Print(){cout << GetName()<< “ is in semester ”<< semester;}May 25, 2013 COMSATS Intitute of Information Technology 466
  • 465. Exampleint main(){Student stdt;stdt.semester = 0;//errorstdt.name = NULL; //errorcout << stdt.GetSemester();cout << stdt.GetName();return 0;}May 25, 2013 COMSATS Intitute of Information Technology 467
  • 466. Allocation in Memory• The object of derived class is represented in memoryas followsMay 25, 2013 COMSATS Intitute of Information Technology 468Data members of baseclassData members ofderived classbase member1base member2...derived member1derived member2...
  • 467. Allocation in Memory• Every object of derived class has an anonymousobject of base classMay 25, 2013 COMSATS Intitute of Information Technology 469
  • 468. Constructors• The anonymous object of base class must beinitialized using constructor of base class• When a derived class object is created theconstructor of base class is executed before theconstructor of derived classMay 25, 2013 COMSATS Intitute of Information Technology 470
  • 469. ConstructorsMay 25, 2013 COMSATS Intitute of Information Technology 471Base class constructorinitializes the anonymousobjectDerived class constructorinitializes the derived classobjectbase member1base member2...derived member1derived member2...
  • 470. Exampleclass Parent{public:Parent(){ cout <<“Parent Constructor...”;}};class Child : public Parent{public:Child(){ cout <<“Child Constructor...”;}};May 25, 2013 COMSATS Intitute of Information Technology 472
  • 471. Exampleint main(){Child cobj;return 0;}May 25, 2013 COMSATS Intitute of Information Technology 473Output:Parent Constructor...Child Constructor...
  • 472. Constructor• If default constructor of base class does not exist thenthe compiler will try to generate a default constructorfor base class and execute it before executingconstructor of derived classMay 25, 2013 COMSATS Intitute of Information Technology 474
  • 473. Constructor•If the user has given only an overloadedconstructor for base class, the compilerwill not generate default constructor forbase classMay 25, 2013 COMSATS Intitute of Information Technology 475
  • 474. Exampleclass Parent{public:Parent(int i){}};class Child : public Parent{public:Child(){}} Child_Object; //ERRORMay 25, 2013 COMSATS Intitute of Information Technology 476
  • 475. Base Class Initializer• C++ has provided a mechanism to explicitly call aconstructor of base class from derived class• The syntax is similar to member initializer and isreferred as base-class initializationMay 25, 2013 COMSATS Intitute of Information Technology 477
  • 476. Exampleclass Parent{public:Parent(int i){…};};class Child : public Parent{public:Child(int i): Parent(i){…}};May 25, 2013 COMSATS Intitute of Information Technology 478
  • 477. Exampleclass Parent{public:Parent(){cout <<“Parent Constructor...”;}...};class Child : public Parent{public:Child():Parent(){cout << “Child Constructor...”;}...};May 25, 2013 COMSATS Intitute of Information Technology 479
  • 478. Base Class Initializer• User can provide base class initializer andmember initializer simultaneouslyMay 25, 2013 COMSATS Intitute of Information Technology 480
  • 479. Exampleclass Parent{public:Parent(){…}};class Child : public Parent{int member;public:Child():member(0), Parent(){…}};May 25, 2013 COMSATS Intitute of Information Technology 481
  • 480. Base Class Initializer• The base class initializer can be written aftermember initializer for derived class• The base class constructor is executed beforethe initialization of data members of derivedclass.May 25, 2013 COMSATS Intitute of Information Technology 482
  • 481. Initializing Members• Derived class can only initialize members of base classusing overloaded constructors• Derived class can not initialize the public datamember of base class using member initializationlistMay 25, 2013 COMSATS Intitute of Information Technology 483
  • 482. Exampleclass Person{public:int age;char *name;...public:Person();};May 25, 2013 COMSATS Intitute of Information Technology 484
  • 483. Exampleclass Student: public Person{private:int semester;...public:Student(int a):age(a){ //error}};May 25, 2013 COMSATS Intitute of Information Technology 485
  • 484. Reason• It will be an assignment not an initializationMay 25, 2013 COMSATS Intitute of Information Technology 486
  • 485. Destructors• Destructors are called in reverse order of constructorcalled• Derived class destructor is called before the base classdestructor is calledMay 25, 2013 COMSATS Intitute of Information Technology 487
  • 486. Exampleclass Parent{public:Parent(){cout <<“Parent Constructor”;}~Parent(){cout<<“Parent Destructor”;}};class Child : public Parent{public:Child(){cout << “Child Constructor”;}~Child(){cout << “Child Destructo”;}};May 25, 2013 COMSATS Intitute of Information Technology 488
  • 487. ExampleOutput:Parent ConstructorChild ConstructorChild DestructorParent DestructorMay 25, 2013 COMSATS Intitute of Information Technology 489
  • 488. Protected Access SpecifierMay 25, 2013 COMSATS Intitute of Information Technology 490
  • 489. Date Classclass Date{int day, month, year;static Date defaultDate;public:void SetDay(int aDay);int GetDay() const;void AddDay(int x);…static void SetDefaultDate(int aDay,int aMonth, int aYear);
  • 490. Date Class...private:bool IsLeapYear();};int main(){Date aDate;aDate.IsLeapYear(); //Errorreturn 0;}
  • 491. Creating SpecialDate ClassSpecial DateDate Special DateAddSpecialYear...
  • 492. Creating SpecialDate Classclass SpecialDate: public Date{…public:void AddSpecialYear(int i){...if(day == 29 && month == 2&& !IsLeapyear(year+i)){ //ERROR!...}}};
  • 493. Modify Access Specifier• We can modify access specifier “IsLeapYear” from private to public
  • 494. Modified Date Classclass Date{public:...bool IsLeapYear();};
  • 495. Modified AddSpecialYearvoid SpecialDate :: AddSpecialYear(int i){...if(day == 29 && month == 2&& !IsLeapyear(year+i)){...}}
  • 496. Protected members• Protected members can not be accessed outside the class• Protected members of base class become protected member ofderived class in Public inheritance
  • 497. Modified Date Classclass Date{…protected:bool IsLeapYear();};int main(){Date aDate;aDate.IsLeapYear(); //Errorreturn 0;}
  • 498. Modified AddSpecialYearvoid SpecialDate :: AddSpecialYear(int i){...if(day == 29 && month == 2&& !IsLeapyear(year+i)){...}}
  • 499. Disadvantages• Breaks encapsulation• The protected member is part of base class’simplementation as well as derived class’s implementation
  • 500. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences ,FAST[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 502
  • 501. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 503
  • 502. CSC241:Object OrientedProgrammingSpring 20131. InheritancePlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 503. Hierarchy of Inheritance• We represent the classes involved in inheritancerelation in tree like hierarchyMay 25, 2013 COMSATS Intitute of Information Technology 505
  • 504. ExampleMay 25, 2013 COMSATS Intitute of Information Technology 506GrandParentParent1 Parent2Child1 Child2
  • 505. Direct Base Class•A direct base class is explicitly listed in aderived classs header with a colon (:)class Child1:public Parent1...May 25, 2013 COMSATS Intitute of Information Technology 507
  • 506. Indirect Base Class•An indirect base class is not explicitly listedin a derived classs header with a colon (:)•It is inherited from two or more levels upthe hierarchy of inheritanceclass GrandParent{};class Parent1:public GrandParent {};class Child1:public Parent1{};May 25, 2013 COMSATS Intitute of Information Technology 508
  • 507. Base Initialization• The child can only perform the initialization of direct base classthrough base class initialization list• The child can not perform the initialization of an indirect base classthrough base class initialization listMay 25, 2013 COMSATS Intitute of Information Technology 509
  • 508. Exampleclass GrandParent{int gpData;public:GrandParent() : gpData(0){...}GrandParent(int i) : gpData(i){...}void Print() const;};May 25, 2013 COMSATS Intitute of Information Technology 510
  • 509. Exampleclass Parent1: public GrandParent{int pData;public:Parent1() : GrandParent(), pData(0) {…}};May 25, 2013 COMSATS Intitute of Information Technology 511
  • 510. Exampleclass Child1 : public Parent1 {public:Child1() : Parent1() {...}Child1(int i) : GrandParent (i) //Error{...}void Print() const;};May 25, 2013 COMSATS Intitute of Information Technology 512
  • 511. Overriding• Child class can override the function of GrandParent classMay 25, 2013 COMSATS Intitute of Information Technology 513
  • 512. ExampleMay 25, 2013 COMSATS Intitute of Information Technology 514GrandParentPrint()Parent1Child1Print()
  • 513. Examplevoid GrandParent::Print() {cout << “GrandParent::Print”<< endl;}void Child1::Print() {cout << “Child1::Print” << endl;}May 25, 2013 COMSATS Intitute of Information Technology 515
  • 514. Exampleint main(){Child1 obj;obj.Print();obj.Parent1::Print();obj.GrandParent::Print();return 0;}May 25, 2013 COMSATS Intitute of Information Technology 516
  • 515. Output• Output is as followsChild1::PrintGrandParent::PrintGrandParent::PrintMay 25, 2013 COMSATS Intitute of Information Technology 517
  • 516. Types of Inheritance• There are three types of inheritance• Public• Protected• Private• Use keyword public, private or protected to specifythe type of inheritanceMay 25, 2013 COMSATS Intitute of Information Technology 518
  • 517. Public InheritanceMember access inBase Class Derived ClassPublic PublicProtected ProtectedPrivate Hiddenclass Child: public Parent {…};
  • 518. Protected InheritanceMember access inBase Class Derived ClassPublic ProtectedProtected ProtectedPrivate Hiddenclass Child: protected Parent {…};
  • 519. Private InheritanceMember access inBase Class Derived ClassPublic PrivateProtected PrivatePrivate Hiddenclass Child: private Parent {…};
  • 520. Private Inheritance• If the user does not specifies the type of inheritance then the defaulttype is private inheritanceclass Child: private Parent {…}is equivalent toclass Child: Parent {…}May 25, 2013 COMSATS Intitute of Information Technology 522
  • 521. Private Inheritance• We use private inheritance when we want to reuse code of someclass• Private Inheritance is used to model “Implemented in terms of”relationshipMay 25, 2013 COMSATS Intitute of Information Technology 523
  • 522. Exampleclass Collection {...public:void AddElement(int);bool SearchElement(int);bool SearchElementAgain(int);bool DeleteElement(int);};May 25, 2013 COMSATS Intitute of Information Technology 524
  • 523. Example• If element is not found in the Collection the function SearchElementwill return false• SearchElementAgain finds the second instance of element in thecollectionMay 25, 2013 COMSATS Intitute of Information Technology 525
  • 524. Class Setclass Set: private Collection {private:...public:void AddMember(int);bool IsMember(int);bool DeleteMember(int);};May 25, 2013 COMSATS Intitute of Information Technology 526
  • 525. Class Setvoid Set::AddMember(int i){if (! IsMember(i) )AddElement(i);}bool Set::IsMember(int i){return SearchElement(i);}May 25, 2013 COMSATS Intitute of Information Technology 527
  • 526. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences ,FAST[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology 528
  • 527. ThanksMay 25, 2013 COMSATS Intitute of Information Technology 529
  • 528. CSC241:Object OrientedProgrammingSpring 20131. Private Inheritance2. SpecializationPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 529. Private Inheritance• If the user does not specifies the type of inheritance then the defaulttype is private inheritanceclass Child: private Parent {…}is equivalent toclass Child: Parent {…}May 25, 2013 COMSATS Intitute of Information Technology
  • 530. Private Inheritance• We use private inheritance when we want to reuse code of someclass• Private Inheritance is used to model “Implemented in terms of”relationshipMay 25, 2013 COMSATS Intitute of Information Technology
  • 531. Exampleclass Collection {...public:void AddElement(int);bool SearchElement(int);bool SearchElementAgain(int);bool DeleteElement(int);};May 25, 2013 COMSATS Intitute of Information Technology
  • 532. Example• If element is not found in the Collection the function SearchElementwill return false• SearchElementAgain finds the second instance of element in thecollectionMay 25, 2013 COMSATS Intitute of Information Technology
  • 533. Class Setclass Set: private Collection {private:...public:void AddMember(int);bool IsMember(int);bool DeleteMember(int);};May 25, 2013 COMSATS Intitute of Information Technology
  • 534. Class Setvoid Set::AddMember(int i){if (! IsMember(i) )AddElement(i);}bool Set::IsMember(int i){return SearchElement(i);}May 25, 2013 COMSATS Intitute of Information Technology
  • 535. Specialization (Restriction)• the derived class is behaviourally incompatible with the base class• Behaviourally incompatible means that base class can’t always bereplaced by the derived classMay 25, 2013 COMSATS Intitute of Information Technology
  • 536. Specialization (Restriction)• Specialization (Restriction) can be implemented using private andprotected inheritanceMay 25, 2013 COMSATS Intitute of Information Technology
  • 537. Example – Specialization(Restriction)May25,2013COMSATSIntituteofInformationTechnologyPersonage : [0..125]Adultage : [18..125]setAge( a )setAge( a )age = aIf age < 18 thenerrorelseage = a
  • 538. Private InheritanceMember access inBase Class Derived ClassPublic PrivateProtected PrivatePrivate Hiddenclass Child: private Parent {…};
  • 539. Exampleclass Person{…protected:int age;public:bool SetAge(int _age){if (_age >=0 && _age <= 125) {age = _age;return true;}return false;}};May 25, 2013 COMSATS Intitute of Information Technology
  • 540. Exampleclass Adult : private Person {public:bool SetAge(int _age){if (_age >=18 && _age <= 125) {age = _age;return true;}return false;}};May 25, 2013 COMSATS Intitute of Information Technology
  • 541. “Abstract” Base Class• In the examples so far, inheritance has been used to add functionalityto an existing class. Now let’s look at an example where inheritance isused for a different purpose: as part of the original design of aprogram.• Our example models a database of employees of a widget company.We’ve simplified the situation so that only three kinds of employeesare represented. Managers manage, scientists perform research todevelop better widgets, and laborers operate the dangerous widget-stamping presses.• The database stores a name and an employee identification numberfor all employees, no matter what their category. However, formanagers, it also stores their titles and golf club dues. For scientists, itstores the number of scholarly articles they have published. Laborersneed no additional data beyond their names and numbers.• Our example program starts with a base class employee. This classhandles the employee’s last name and employee number. From thisclass three other classes are derived: manager, scientist, and laborer.The manager and scientist classes contain additional informationabout these categories of employee, and member functions to handlethis information, as shown in FigureMay 25, 2013 COMSATS Intitute of Information Technology
  • 542. May 25, 2013 COMSATS Intitute of Information Technology
  • 543. Exercise 1• Imagine a publishing company that markets both book andaudiocassette versions of its works. Create a class publication thatstores the title (a string) and price (type float) of a publication. Fromthis class derive two classes: book, which adds a page count (typeint), and tape, which adds a playing time in minutes (type float). Eachof these three classes should have a getdata() function to get its datafrom the user at the keyboard, and a putdata() function to display itsdata. Write a main() program to test the book and tape classes bycreating instances of them, asking the user to fill in data withgetdata(), and then displaying the data with putdata().May 25, 2013 COMSATS Intitute of Information Technology
  • 544. Exercise 2• Start with the publication, book, and tape classes of Exercise 1. Add abase class sales that holds an array of three floats so that it can recordthe dollar sales of a particular publication for the last three months.Include a getdata() function to get three sales amounts from the user,and a putdata() function to display the sales figures. Alter the bookand tape classes so they are derived from both publication and sales.An object of class book or tape should input and output sales dataalong with its other data. Write a main() function to create a bookobject and a tape object and exercise their input/output capabilities.May 25, 2013 COMSATS Intitute of Information Technology
  • 545. Exercise 3• Assume that the publisher in Exercises 1 and 3 decides to add a thirdway to distribute books: on computer disk, for those who like to dotheir reading on their laptop. Add a disk class that, like book and tape,is derived from publication. The disk class should incorporate thesame member functions as the other classes. The data item unique tothis class is the disk type: either CD or DVD. You can use an enum typeto store this item. The user could select the appropriate type bytyping c or d.May 25, 2013 COMSATS Intitute of Information Technology
  • 546. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences ,FAST[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Intitute of Information Technology
  • 547. ThanksMay 25, 2013 COMSATS Intitute of Information Technology
  • 548. CSC241:Object OrientedProgrammingSpring 20131. Overriding & Overloading2. Multiple Inheritance3. Virtual Inheritance4. Virtual Functions/MembersPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 549. Overriding Member Functions of BaseClass• Derived class can override the member functions ofits base class• To override a function the derived class simplyprovides a function with the same signature as that ofits base classMay 25, 2013 COMSATS Institute of Information Technology 553
  • 550. OverridingMay 25, 2013 COMSATS Institute of Information Technology 554Parent...Func1Child...Func1
  • 551. Overridingclass Parent {public:voidFunc1();voidFunc1(int);};class Child: public Parent {public:void Func1();};May 25, 2013 COMSATS Institute of Information Technology 555
  • 552. Overloading vs. Overriding• Overloading is done within the scope of one class• Overriding is done in scope of parent and child• Overriding within the scope of single class is error due to duplicatedeclarationMay 25, 2013 COMSATS Institute of Information Technology 556
  • 553. Overridingclass Parent {public:void Func1();void Func1(); //Error};May 25, 2013 COMSATS Institute of Information Technology 557
  • 554. Overriding Member Functions of BaseClass• Derive class can override member function of baseclass such that the working of function is totallychangedMay 25, 2013 COMSATS Institute of Information Technology 558
  • 555. Exampleclass Person{public:void Walk();};class ParalyzedPerson: public Person{public:void Walk();};May 25, 2013 COMSATS Institute of Information Technology 559
  • 556. Overriding Member Functions of BaseClass• Derive class can override member function of baseclass such that the working of function is similar toformer implementationMay 25, 2013 COMSATS Institute of Information Technology 560
  • 557. Exampleclass Person{char *name;public:Person(char *=NULL);const char *GetName() const;void Print(){cout << “Name: ” << name<< endl;}};May 25, 2013 COMSATS Institute of Information Technology 561
  • 558. Exampleclass Student : public Person{char * major;public:Student(char * aName, char* aMajor);void Print(){cout <<“Name: ”<< GetName()<<endl<< “Major:” << major<< endl;}...};May 25, 2013 COMSATS Institute of Information Technology 562
  • 559. Exampleint main(){Student a(“Ahmad”, “ComputerScience”);a.Print();return 0;}May 25, 2013 COMSATS Institute of Information Technology 563
  • 560. OutputOutput:Name: AhmedMajor: Computer ScienceMay 25, 2013 COMSATS Institute of Information Technology 564
  • 561. Overriding Member Functions of BaseClass• Derive class can override member function of baseclass such that the working of function is based onformer implementationMay 25, 2013 COMSATS Institute of Information Technology 565
  • 562. Exampleclass Student : public Person{char * major;public:Student(char * aName, char* m);void Print(){Print();//Print of Personcout<<“Major:” << major <<endl;}...};May 25, 2013 COMSATS Institute of Information Technology 566
  • 563. Exampleint main(){Student a(“Ahmad”, “ComputerScience”);a.Print();return 0;}May 25, 2013 COMSATS Institute of Information Technology 567
  • 564. Output• There will be no output as the compiler will call theprint of the child class from print of child classrecursively• There is no ending conditionMay 25, 2013 COMSATS Institute of Information Technology 568
  • 565. Exampleclass Student : public Person{char * major;public:Student(char * aName, char* m);void Print(){Person::Print();cout<<“Major:” << major <<endl;}...};May 25, 2013 COMSATS Institute of Information Technology 569
  • 566. Exampleint main(){Student a(“Ahmad”, “ComputerScience”);a.Print();return 0;}May 25, 2013 COMSATS Institute of Information Technology 570
  • 567. OutputOutput:Name: AhmedMajor: Computer ScienceMay 25, 2013 COMSATS Institute of Information Technology 571
  • 568. {Before New Topic……}• I need Your anonymous Feed Back• About the Instructor•&• About the CourseMay 25, 2013 COMSATS Institute of Information Technology 572
  • 569. Multiple Inheritance• A class can inherit from more then one classMay 25, 2013 COMSATS Institute of Information Technology 573
  • 570. Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 574Transmitter...Transmit()Receiver...Receive()Phone
  • 571. Exampleclass Phone: public Transmitter, publicReceiver{...};May 25, 2013 COMSATS Institute of Information Technology 575
  • 572. Multiple Inheritance• Derived class can inherit from public base class as well as private andprotected base classesclass Mermaid:private Woman, private FishMay 25, 2013 COMSATS Institute of Information Technology 576
  • 573. Multiple Inheritance• The derived class inherits data members and functions form all thebase classes• Object of derived class can perform all the tasks that an object ofbase class can performMay 25, 2013 COMSATS Institute of Information Technology 577
  • 574. Exampleint main(){Phone obj;obj.Transmit();obj.Receive();return 0;}May 25, 2013 COMSATS Institute of Information Technology 578
  • 575. Multiple Inheritance• When using public multiple inheritance, the object of derived classcan replace the objects of all the base classesMay 25, 2013 COMSATS Institute of Information Technology 579
  • 576. Exampleint main(){Phone obj;Transmitter * tPtr = &obj;Receiver * rPtr = &obj;return 0;}May 25, 2013 COMSATS Institute of Information Technology 580
  • 577. Multiple Inheritance• The pointer of one base class cannot be used to call the function ofanother base class• The functions are called based on static typeMay 25, 2013 COMSATS Institute of Information Technology 581
  • 578. Exampleint main(){Phone obj;Transmitter * tPtr = &obj;tPtr->Transmit();tPtr->Receive(); //Errorreturn 0;}May 25, 2013 COMSATS Institute of Information Technology 582
  • 579. Exampleint main(){Phone obj;Receiver * rPtr = &obj;rPtr->Receive();rPtr->Transmit(); //Errorreturn 0;}May 25, 2013 COMSATS Institute of Information Technology 583
  • 580. Multiple Inheritance• If more than one base class have a function with same signature thenthe child will have two copies of that function• Calling such function will result in ambiguityMay 25, 2013 COMSATS Institute of Information Technology 584
  • 581. Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 585AmphibiousVehicleLand Vehicle Water VehicleCar Boat
  • 582. Exampleclass LandVehicle{public:int GetMaxLoad();};class WaterVehicle{public:int GetMaxLoad();};May 25, 2013 COMSATS Institute of Information Technology 586
  • 583. Exampleclass AmphibiousVehicle:public LandVehicle,public WaterVehicle{};int main(){AmphibiousVehicle obj;obj.GetMaxLoad(); // Errorreturn 0;}May 25, 2013 COMSATS Institute of Information Technology 587
  • 584. Multiple Inheritance• Programmer must explicitly specify the class name when callingambiguous functionMay 25, 2013 COMSATS Institute of Information Technology 588
  • 585. Exampleint main(){AmphibiousVehicle obj;obj.LandVehicle::GetMaxLoad();obj.WaterVehicle::GetMaxLoad();return 0;}May 25, 2013 COMSATS Institute of Information Technology 589
  • 586. Multiple Inheritance• The ambiguous call problem can arise when dealing with multiplelevel of multiple inheritanceMay 25, 2013 COMSATS Institute of Information Technology 590
  • 587. Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 591AmphibiousVehicleLand Vehicle Water VehicleVehicleCar Boat
  • 588. Exampleclass Vehicle{public:int GetMaxLoad();};class LandVehicle : public Vehicle{};class WaterVehicle : public Vehicle{};May 25, 2013 COMSATS Institute of Information Technology 592
  • 589. Exampleclass AmphibiousVehicle:public LandVehicle,public WaterVehicle{};int main(){AmphibiousVehicle obj;obj.GetMaxLoad(); // Errorreturn 0;}May 25, 2013 COMSATS Institute of Information Technology 593
  • 590. Exampleint main(){AmphibiousVehicle obj;obj.Vehicle::GetMaxLoad(); //Errorreturn 0;}•Vehicle is accessible through two pathsMay 25, 2013 COMSATS Institute of Information Technology 594
  • 591. Multiple InheritanceMay 25, 2013 COMSATS Institute of Information Technology 595AmphibiousVehicleLand Vehicle Water VehicleVehicleCar BoatVehicle
  • 592. Exampleint main(){AmphibiousVehicle obj;obj.LandVehicle::GetMaxLoad();obj.WaterVehicle::GetMaxLoad();return 0;}May 25, 2013 COMSATS Institute of Information Technology 596
  • 593. Multiple Inheritance• Data member must be used with care when dealing with more thenone level on inheritanceMay 25, 2013 COMSATS Institute of Information Technology 597
  • 594. Exampleclass Vehicle{protected:int weight;};class LandVehicle : public Vehicle{};class WaterVehicle : public Vehicle{};May 25, 2013 COMSATS Institute of Information Technology 598
  • 595. Exampleclass AmphibiousVehicle:public LandVehicle,public WaterVehicle{public:AmphibiousVehicle(){LandVehicle::weight = 10;WaterVehicle::weight = 10;}};• There are multiple copies of data member weightMay 25, 2013 COMSATS Institute of Information Technology 599
  • 596. Memory ViewMay25,2013COMSATSInstituteofInformationTechnology600Data Members ofVehicleData Members ofLandVehicleData Members of AmphibiousVehicleData Members ofVehicleData Members ofWaterVehicle
  • 597. Virtual Inheritance• In virtual inheritance there is exactly one copy of the anonymous baseclass objectMay 25, 2013 COMSATS Institute of Information Technology 601
  • 598. Exampleclass Vehicle{protected:int weight;};class LandVehicle :public virtual Vehicle{};class WaterVehicle :public virtual Vehicle{};May 25, 2013 COMSATS Institute of Information Technology 602
  • 599. Exampleclass AmphibiousVehicle:public LandVehicle,public WaterVehicle{public:AmphibiousVehicle(){weight = 10;}};May 25, 2013 COMSATS Institute of Information Technology 603
  • 600. Memory ViewMay 25, 2013 COMSATS Institute of Information Technology 604Data Members of VehicleData Members ofLandVehicleData Members of AmphibiousVehicleData Members ofWaterVehicle
  • 601. Virtual Inheritance• Virtual inheritance must be used when necessary• There are situation when programmer would want to use two distinctdata members inherited from base class rather then oneMay 25, 2013 COMSATS Institute of Information Technology 605
  • 602. ExampleMay 25, 2013 COMSATS Institute of Information Technology 606StudentBS Student MS Student PhD StudentMS/PhD StudentGPA
  • 603. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences ,FAST[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Institute of Information Technology 607
  • 604. ThanksMay 25, 2013 COMSATS Institute of Information Technology 608
  • 605. CSC241:Object OrientedProgrammingSpring 20131. Generic Programming2. TemplatesPlease turn OFF your Mobile Phones!Saturday, May 25, 2013Farhan Aadil
  • 606. Quiz• Explain “Diamond of Death” with help of Class Diagram, also writecode for your class diagram.May 25, 2013 COMSATS Institute of Information Technology 610
  • 607. Feed Back• High level course , contents , lectures assignments etc etc• Level of class/students ….• Too much course contents---- ???? What???• ITP Semester 1, Check Concepts• Basic concepts…. Should I start the ITP again???• 1 concept 1 topic 1 program per class --- Nice Joke ;-)• Questions during lectures-OK Noted• Programs, programs, & programs , …..and then coding• Where is the Theory?????• Revision Classes --- ok Sure, when ??? Tell me• Shortcuts ---- (There is no shortcut in life BTW )• Attention to backbenchers --- How can I do that??May 25, 2013 COMSATS Institute of Information Technology 611
  • 608. Feed Back ……• Tough time , assignments, project why us????• Don’t get angry why? --• Body language ….. Well  concentrate more on the course ;-)• Entertain students ….well exactly how? can u explain ;-)• Practical life, students doing masti during lectures…• Fast speed…Why, seems to b in hurry always ???• Faviourism , u r not neutral…• Not all students are programmers most of them are normal human beings, ;;;;• Not put your self in a situation so that u have to…….• -----------• Dress code for presentation…May 25, 2013 COMSATS Institute of Information Technology 612
  • 609. Motivation• Following function prints an array of integer elements:void printArray(int* array, int size){for ( int i = 0; i < size; i++ )cout << array[ i ] << “, ”;}
  • 610. ...Motivation• What if we want to print an array of characters?void printArray(char* array,int size){for ( int i = 0; i < size; i++ )cout << array[ i ] << “, ”;}
  • 611. ...Motivation• What if we want to print an array of doubles?void printArray(double* array,int size){for ( int i = 0; i < size; i++ )cout << array[ i ] << “, ”;}
  • 612. ...Motivation• Now if we want to change the way function prints the array. e.g. from1, 2, 3, 4, 5to1 - 2 - 3 - 4 - 5
  • 613. ...Motivation• Now consider the Array class that wraps an array of integersclass Array {int* pArray;int size;public:…};
  • 614. ...Motivation• What if we want to use an Array class that wraps arrays of double?class Array {double* pArray;int size;public:…};
  • 615. ...Motivation• What if we want to use an Array class that wraps arrays of booleanvariables?class Array {bool* pArray;int size;public:…};
  • 616. ...Motivation• Now if we want to add a function sum to Array class, we have tochange all the three classes
  • 617. Generic Programming• Generic programming refers to programs containing genericabstractions• A generic program abstraction (function, class) can be parameterizedwith a type• Such abstractions can work with many different types of data
  • 618. Advantages• Reusability• Writability• Maintainability
  • 619. Templates• In C++ generic programming is done using templates• Two kinds• Function Templates• Class Templates• Compiler generates different type-specific copies from a singletemplate
  • 620. Function Templates• A function template can be parameterized to operate on differenttypes of data
  • 621. Declarationtemplate< class T >void funName( T x );// ORtemplate< typename T >void funName( T x );// ORtemplate< class T, class U, … >void funName( T x, U y, … );
  • 622. Example – Function Templates• Following function template prints an array having almost any type ofelements:template< typename T >void printArray( T* array, int size ){for ( int i = 0; i < size; i++ )cout << array[ i ] << “, ”;}
  • 623. …Example – Function Templatesint main() {int iArray[5] = { 1, 2, 3, 4, 5 };void printArray( iArray, 5 );// Instantiated for int[]char cArray[3] = { „a‟, „b‟, „c‟ };void printArray( cArray, 3 );// Instantiated for char[]return 0;}
  • 624. Explicit Type Parameterization• A function template may not have any parametertemplate <typename T>T getInput() {T x;cin >> x;return x;}
  • 625. …Explicit Type Parameterizationint main() {int x;x = getInput(); // Error!double y;y = getInput(); // Error!}
  • 626. …Explicit Type Parameterizationint main() {int x;x = getInput< int >();double y;y = getInput< double >();}
  • 627. User-defined Specializations• A template may not handle all the types successfully• Explicit specializations need to be provided for specific type(s)
  • 628. Example – User Specializationstemplate< typename T >bool isEqual( T x, T y ) {return ( x == y );}
  • 629. … Example – User Specializationsint main {isEqual( 5, 6 );// OKisEqual( 7.5, 7.5 ); // OKisEqual( “abc”, “xyz” );// Logical Error!return 0;}
  • 630. … Example – User Specializationstemplate< >bool isEqual< const char* >(const char* x, const char* y ) {return ( strcmp( x, y ) == 0 );}
  • 631. … Example – User Specializationsint main {isEqual( 5, 6 );// Target: general templateisEqual( 7.5, 7.5 );// Target: general templateisEqual( “abc”, “xyz” );// Target: user specializationreturn 0;}
  • 632. References• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (TheWaite Group). 4th ed. available in soft form.• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology,Cengage Learning. 4th ed. available in soft form• National University of Computer & Emerging Sciences ,FAST[www.nu.edu.pk]• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium[http://www.ocwconsortium.org/en/courses]May 25, 2013 COMSATS Institute of Information Technology 637
  • 633. ThanksMay 25, 2013 COMSATS Institute of Information Technology 638
  • 634. LEC 20 TEMPLATE.CPP• // function template• #include <iostream>• using namespace std;• template <class T>• T GetMax (T a, T b)• {• T result;• result = (a>b)? a : b;• return (result);• }• int main ()• {• int i=5, j=6, k;• float l=10.5, m=5.6, n;• k=GetMax< int >(i,j);• n=GetMax< float >(l,m);•• cout << k << endl;• cout << n << endl;• return 0;• }
  • 635. EXE LEC 18` // exp09_04.cpp (pub3)// three classes derived from publication class#include <iostream>#include <string>using namespace std;enum disktype {CD, DVD};////////////////////////////////////////////////////////////////class publication{private:string title;float price;public:void getdata(){cout << "n Enter title (one word only): ";