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
• Procedural
Withdraw, deposit, transfer
• Object Oriented
Customer, money, account
May 25, 2013 COMSATS Institute of Information Technology 4
6. What is Object-Orientation?
• A technique for system modeling
• OO model consists of several interacting objects
May 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 it
May 25, 2013 COMSATS Institute of Information Technology 7
8. Examples – Model
• Highway maps
• Architectural models
• Mechanical models
May 25, 2013 COMSATS Institute of Information Technology 8
9. Example – OO Model
May 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 car
May 25, 2013 COMSATS Institute of Information Technology 10
Ali
Car
House
Tree
lives-in
drives
11. Object-Orientation - Advantages
• People think in terms of objects
• OO models map to reality
• Therefore, OO models are
• easy to develop
• easy to understand
May 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 identity
May 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 name
May 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 number
May 25, 2013 COMSATS Institute of Information Technology 15
16. Example – Time is an Object Apprehended
Intellectually
• State (attributes)
- Hours - Seconds
- Minutes
• behaviour (operations)
- Set Hours - Set Seconds
- Set Minutes
• Identity
- Would have a unique ID in the model
May 25, 2013 COMSATS Institute of Information Technology 16
17. Example – Date is an Object Apprehended
Intellectually
• State (attributes)
- Year - Day
- Month
• behaviour (operations)
- Set Year - Set Day
- Set Month
• Identity
- Would have a unique ID in the model
May 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 find
in everyday life.
• Objects are key to understanding object-oriented technology. You can
look 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-world
objects
• A software object maintains its state in one or more variables .
• A software object implements its behavior with methods . A method
is a function (subroutine) associated with an object.
May 25, 2013 COMSATS Institute of Information Technology 20
21. Can represent real-world objects by using
software objects.
• You might want to represent real-world dogs as software objects in an
animation program or a real-world bicycle as a software object in the
program that controls an electronic exercise bike.
• You can also use software objects to model abstract concepts. For
example, an event is a common object used in GUI window systems to
represent the action of a user pressing a mouse button or a key on
the 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 of
instructions.
• Very small programs (tens of lines) need no organization.
• As they get large (hundreds of lines), they are divided into
functions.
• Functions are still lists of instructions.
• Dividing a program into functions gives a structure to the
program (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 a
logical group or show any form of binding.
• Cannot model ‘real world’.
• In real world, we deal with objects like cars, people
etc.
• Are such objects like ‘data’? Which data type describes a
car, 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’ to
represent its specifications or ‘attributes’ only? For
example what attributes describe a car?
• So by having all these attributes ‘only’ do you know all
about a car? Would you buy a car by merely looking at
these 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 braking
etc.
• Effectively, you wish to know how it ‘functions’.
• Behaviour is like a function.
• So neither data nor functions, by themselves, model
real-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. So
data gets ‘hidden’.
• Data hiding ensures the data is not accidentally altered.
• Reference analogy of a growing company; 2 people vs 100
employee company.
• Objects communicate with each other by calling each
other’s member functions.
May 25, 2013 COMSATS Institute of Information Technology 26
27. Object Oriented Approach …
• OOP is all about ‘organization’ and not about program
operation. Most individual statements are similar to C
statements. Member functions may be very similar to
C 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. Honda
City 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 current
perspective”
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 - Age
May 25, 2013 COMSATS Institute of Information Technology 29
Ali is a PhD student and teaches BS students
30. Example – Abstraction
• behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
May 25, 2013 COMSATS Institute of Information Technology 30
Ali is a PhD student and teaches BS students
31. Example – Abstraction
Attributes
• - Name - Employee ID
• - Student Roll No - Designation
• - Year of Study - Salary
• - CGPA - Age
May 25, 2013 COMSATS Institute of Information Technology 31
Student’s Perspective
32. Example – Abstraction
• behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
May 25, 2013 COMSATS Institute of Information Technology 32
Student’s Perspective
33. Example – Abstraction
• Attributes
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age
May 25, 2013 COMSATS Institute of Information Technology 33
Teacher’s Perspective
34. Example – Abstraction
• behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
May 25, 2013 COMSATS Institute of Information Technology 34
Teacher’s Perspective
35. Example – Abstraction
• Ordinary Perspective
A pet animal with
• Four Legs
• A Tail
• Two Ears
• Sharp Teeth
• Surgeon’s Perspective
A being with
• A Skeleton
• Heart
• Kidney
• Stomach
May 25, 2013 COMSATS Institute of Information Technology 35
A cat can be viewed with different perspectives
36. Example – Abstraction
May 25, 2013 COMSATS Institute of Information Technology 36
Driver’s View
Engineer’s View
37. Abstraction – Advantages
• Simplifies the model by hiding irrelevant details
• Abstraction provides the freedom to defer implementation decisions
by avoiding commitment to details
May 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 class
May 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 class
May 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 class
May 25, 2013 COMSATS Institute of Information Technology 40
41. Graphical Representation of Classes
May 25, 2013 COMSATS Institute of Information Technology 41
(Class Name)
(attributes)
(operations)
(Class Name)
Normal Form
Suppressed
Form
42. Example – Graphical Representation of
Classes
May 25, 2013 COMSATS Institute of Information Technology 42
Circle
center
radius
draw
computeArea
Normal Form
Suppressed
Form
Circle
43. Example – Graphical Representation of
Classes
May 25, 2013 COMSATS Institute of Information Technology 43
Person
name
age
gender
eat
walk
Normal Form
Suppressed
Form
Person
44. Inheritance
• A child inherits characteristics of its parents
• Besides inherited characteristics, a child may have its own unique
characteristics
May 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 called
derived class
• Besides inherited characteristics, derived class may have its own
unique characteristics
May 25, 2013 COMSATS Institute of Information Technology 45
46. Example – Inheritance
May 25, 2013 COMSATS Institute of Information Technology 46
Person
Teacher
DoctorStudent
47. Example – Inheritance
May 25, 2013 COMSATS Institute of Information Technology 47
Shape
Circle
TriangleLine
48. Inheritance – “IS A” or
“IS A KIND OF” Relationship
• Each derived class is a special kind of its base class
May 25, 2013 COMSATS Institute of Information Technology 48
49. Example – “IS A” Relationship
May 25, 2013 COMSATS Institute of Information Technology 49
Person
name
age
gender
eat
walk
Teacher
designation
salary
teach
takeExam
Student
program
studyYear
study
heldExam
Doctor
designation
salary
checkUp
prescribe
50. Example – “IS A” Relationship
May 25, 2013 COMSATS Institute of Information Technology 50
Shape
color
coord
draw
rotate
setColor
Circle
radius
draw
computeArea
Line
length
draw
Triangle
angle
draw
computeArea
51. Inheritance – Advantages
• Reuse
• Less redundancy
• Increased maintainability
May 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 functionality
May 25, 2013 COMSATS Institute of Information Technology 52
53. Example Reuse
May 25, 2013 COMSATS Institute of Information Technology 53
Shape
color
coord
draw
rotate
setColor
Circle
radius
draw
computeArea
Line
length
draw
Triangle
angle
draw
computeArea
54. Example Reuse
May 25, 2013 COMSATS Institute of Information Technology 54
Person
name
age
gender
eat
walk
Teacher
designation
salary
teach
takeExam
Student
program
studyYear
study
heldExam
Doctor
designation
salary
checkUp
prescribe
55. Example Reuse
May 25, 2013 COMSATS Institute of Information Technology 55
Person
name
age
gender
eat
walk
Teacher
designation
salary
teach
takeExam
Student
program
studyYear
study
heldExam
Doctor
designation
salary
checkUp
prescribe
56. References
• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (The
Waite 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,2013COMSATSInstituteofInformationTechnology
56
58. CSC241:
Object Oriented
Programming
Spring 2013
1. Inheritance & Generalization
May25,2013COMSATSInstituteofInformationTechnology
58
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
59. Recap – Inheritance
• Derived class inherits all the characteristics of the base class
• Besides inherited characteristics, derived class may have its own
unique characteristics
• Major benefit of inheritance is reuse
May 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 classes
from this new class
• This concept is known as Generalization
May 25, 2013 COMSATS Institute of Information Technology 61
62. Example – Generalization
May 25, 2013 COMSATS Institute of Information Technology 62
Circle
color
vertices
radius
move
setColor
computeArea
Line
color
vertices
length
move
setColor
getLength
Triangle
color
vertices
angle
move
setColor
computeArea
63. Example – Generalization
May 25, 2013 COMSATS Institute of Information Technology 63
Shape
color
vertices
move
setColor
Circle
radius
computeArea
Line
length
getLength
Triangle
angle
computeArea
64. Example – Generalization
May 25, 2013 COMSATS Institute of Information Technology 64
Teacher
name
age
gender
designation
salary
teach
takeExam
eat
walk
Student
name
age
gender
program
studyYear
study
heldExam
eat
walk
Doctor
name
age
gender
designation
salary
checkUp
prescribe
eat
walk
65. Example – Generalization
May 25, 2013 COMSATS Institute of Information Technology 65
Person
name
age
gender
eat
walk
Teacher
designation
salary
teach
takeExam
Student
program
studyYear
study
heldExam
Doctor
designation
salary
checkUp
prescribe
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 desired
state and behaviour
• Inherit the new class from this class and add unique behaviour to the
new class
May 25, 2013 COMSATS Institute of Information Technology 66
67. Sub-typing (Extension)
• Sub-typing means that derived class is behaviourally compatible with
the base class
• Behaviourally compatible means that base class can be replaced by
the derived class
May 25, 2013 COMSATS Institute of Information Technology 67
68. Example –
Sub-typing
(Extension)
May 25, 2013 COMSATS Institute of Information Technology 68
Person
name
age
gender
eats
walks
Student
program
studyYear
study
takeExam
69. Example –
Sub-typing
(Extension)
May 25, 2013 COMSATS Institute of Information Technology 69
Shape
color
vertices
setColor
move
Circle
radius
computeCF
computeArea
70. Specialization (Restriction)
• Specialization means that derived class is behaviourally incompatible
with the base class
• Behaviourally incompatible means that base class can’t always be
replaced by the derived class
May 25, 2013 COMSATS Institute of Information Technology 70
71. Example – Specialization
(Restriction)
May 25, 2013 COMSATS Institute of Information Technology 71
Person
age : [0..100]
…
Adult
age : [18..100]
…
setAge( a )
…
setAge( a )
…
age = a
If age < 18 then
error
else
age = a
72. Example – Specialization
(Restriction)
May 25, 2013 COMSATS Institute of Information Technology 72
IntegerSet
…
NaturalSet
…
add( elem )
…
add( elem )
…
add element
to the set
If elem < 1 then
error
else
add element
to the set
73. Overriding
• A class may need to override the default behaviour provided by its
base class
• Reasons for overriding
• Provide behaviour specific to a derived class
• Extend the default behaviour
• Restrict the default behaviour
• Improve performance
May 25, 2013 COMSATS Institute of Information Technology 73
74. Example – Specific Behaviour
May 25, 2013 COMSATS Institute of Information Technology 74
Shape
color
vertices
draw
move
setColor
Circle
radius
draw
computeArea
Line
length
draw
Triangle
angle
draw
computeArea
75. Example – Extension
May 25, 2013 COMSATS Institute of Information Technology 75
Window
width
height
open
close
draw
DialogBox
controls
enable
draw
1- Invoke Window’s
draw
2- draw the dialog
box
76. Example – Restriction
May 25, 2013 COMSATS Institute of Information Technology 76
IntegerSet
…
NaturalSet
…
add( elem )
…
add( elem )
…
Add element to
the set
If elem < 1 then
give error
else
Add element to
the set
77. Example – Improve Performance
• Class Circle overrides
rotate operation of class
Shape with a Null
operation.
May 25, 2013 COMSATS Institute of Information Technology 77
Shape
color
coord
draw
rotate
setColor
Circle
radius
draw
rotate
78. Abstract Classes
• An abstract class implements an abstract concept
• Main purpose is to be inherited by other classes
• Can’t be instantiated
• Promotes reuse
May 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 79
Teacher
DoctorStudent
Person
name
age
gender
eat
walk
80. Example – Abstract Classes
• Here, Vehicle is an abstract classMay 25, 2013 COMSATS Institute of Information Technology 80
Bus
TruckCar
Vehicle
color
model
accelerate
applyBrakes
81. Concrete Classes
• A concrete class implements a concrete concept
• Main purpose is to be instantiated
• Provides implementation details specific to the domain context
May 25, 2013 COMSATS Institute of Information Technology 81
82. Example – Concrete Classes
• Here, Student, Teacher and Doctor are concrete
classesMay 25, 2013 COMSATS Institute of Information Technology 82
Teacher
DoctorStudent
program
studyYear
study
heldExam
Person
83. Example – Concrete Classes
May 25, 2013 COMSATS Institute of Information Technology 83
• Here, Car, Bus and Truck are concrete classes
Bus
Car
Vehicle
Truck
capacity
load
unload
84. Multiple Inheritance
• We may want to reuse characteristics of more than one parent class
May 25, 2013 COMSATS Institute of Information Technology 84
85. Example – Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 85
Mermaid
86. Example – Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 86
Mermaid
Woman Fish
87. Example – Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 87
Amphibious Vehicle
88. Example – Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 88
Amphibious Vehicle
Land Vehicle Water Vehicle
Vehicle
Car Boat
89. Problems with Multiple Inheritance
• Increased complexity
• Reduced understanding
• Duplicate features
May 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 90
Mermaid
Woman Fish
eat
…
eat
…
91. Solution – Override the Common Feature
May 25, 2013 COMSATS Institute of Information Technology 91
Mermaid
Woman Fish
eat
…
eat
…
eat
…
Invoke eat
operation of
desired class
92. Problem – Duplicate Features
(Diamond Problem)
• Which changeGear operation Amphibious Vehicle
inherits?
May 25, 2013 COMSATS Institute of Information Technology 92
Amphibious Vehicle
Land Vehicle Water Vehicle
Vehicle
Car Boat
changeGear
93. Solution to Diamond Problem
• Some languages disallow diamond hierarchy
• Others provide mechanism to ignore characteristics
from one side
May 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 tasks
May 25, 2013 COMSATS Institute of Information Technology 94
95. Kinds of Association
• Class Association
• Inheritance
• Object Association
• Simple Association
• Composition
• Aggregation
May 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 other
object
• 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 Association
May 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 object
May 25, 2013 COMSATS Institute of Information Technology 98
99. Example – Association
• Ali lives in a House
May 25, 2013 COMSATS Institute of Information Technology 99
Ali House
lives-in
11
100. Example – Association
• Ali drives his Car
May 25, 2013 COMSATS Institute of Information Technology 100
Ali Car
drives
*1
101. Two-way Association
• We can navigate in both directions
• Denoted by a line between the associated objects
May 25, 2013 COMSATS Institute of Information Technology 101
102. Example – Two-way Association
• Employee works for company
• Company employs employees
May 25, 2013 COMSATS Institute of Information Technology 102
Employee Company
works-for
1*
103. Example – Two-way Association
• Yasir is a friend of Ali
• Ali is a friend of Yasir
May 25, 2013 COMSATS Institute of Information Technology 103
Yasir Ali
friend
11
104. Binary Association
• Associates objects of exactly two classes
• Denoted by a line, or an arrow between the associated objects
May 25, 2013 COMSATS Institute of Information Technology 104
105. Example – Binary Association
• Association “works-for” associates objects of exactly
two classes
May 25, 2013 COMSATS Institute of Information Technology 105
Employee Company
works-for
1*
106. Example – Binary Association
• Association “drives” associates objects of exactly two
classes
May 25, 2013 COMSATS Institute of Information Technology 106
Ali Car
drives
*1
107. Ternary Association
• Associates objects of exactly three classes
• Denoted by a diamond with lines connected to associated objects
May 25, 2013 COMSATS Institute of Information Technology 107
108. Example – Ternary Association
• Objects of exactly three classes are associated
May 25, 2013 COMSATS Institute of Information Technology 108
Student Teacher
Course
1
*
*
109. Example – Ternary Association
• Objects of exactly three classes are associated
May 25, 2013 COMSATS Institute of Information Technology 109
Project Language
Person
*
1
*
110. N-ary Association
• An association between 3 or more classes
• Practical examples are very rare
May 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” object
is known as Composition
• Composition is represented by a line with a filled-diamond head
towards the composer object
May 25, 2013 COMSATS Institute of Information Technology 111
112. Example – Composition of Ali
May 25, 2013 COMSATS Institute of Information Technology 112
Ali
Body
Arm
Head
Leg
1
1
2 2
113. Example – Composition of Chair
May 25, 2013 COMSATS Institute of Information Technology 113
Chair
SeatArm
Back
Leg
1
12 4
114. Composition is Stronger
• Composition is a stronger relationship, because
• Composed object becomes a part of the composer
• Composed object can’t exist independently
May 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 Ali
May 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 independently
May 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 is
called aggregation
• Aggregation is represented by a line with unfilled-diamond head
towards the container
May 25, 2013 COMSATS Institute of Information Technology 117
118. Example – Aggregation
May 25, 2013 COMSATS Institute of Information Technology 118
Room
Cupboard
Bed
Chair Table
*
1
1
1
120. Aggregation is Weaker
• Aggregation is weaker relationship, because
• Aggregate object is not a part of the container
• Aggregate object can exist independently
May 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 exist
independent of a particular room
May 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 independent
of a particular garden
May 25, 2013 COMSATS Institute of Information Technology 122
123. References
• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (The
Waite 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,2013COMSATSInstituteofInformationTechnology
123
125. CSC241:
Object Oriented
Programming
Spring 2013
1. Inheritance Concepts
2. Polymorphism
May 25, 2013 COMSATS Intitute of Information Technology
125
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
126. Class diagram showing
inheritance
May 25, 2013 COMSATS Intitute of Information Technology 126
Inheritance among classes is
shown as open triangular
arrowhead in UML Class
Diagram.
Arrow be read as “derived
from”.
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 tasks
May 25, 2013 COMSATS Intitute of Information Technology 127
128. Kinds of Association
• Class Association
• Inheritance
• Object Association
• Simple Association
• Composition
• Aggregation
May 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 other
object
• 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 Association
May 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 object
May 25, 2013 COMSATS Intitute of Information Technology 131
132. Example – Association
• Ali lives in a House
May 25, 2013 COMSATS Intitute of Information Technology 132
Ali House
lives-in
11
133. Example – Association
• Ali drives his Car
May 25, 2013 COMSATS Intitute of Information Technology 133
Ali Car
drives
*1
134. Two-way Association
• We can navigate in both directions
• Denoted by a line between the associated objects
May 25, 2013 COMSATS Intitute of Information Technology 134
135. Example – Two-way Association
• Employee works for company
• Company employs employees
May 25, 2013 COMSATS Intitute of Information Technology 135
Employee Company
works-for
1*
136. Example – Two-way Association
• Yasir is a friend of Ali
• Ali is a friend of Yasir
May 25, 2013 COMSATS Intitute of Information Technology 136
Yasir Ali
friend
11
137. Binary Association
• Associates objects of exactly two classes
• Denoted by a line, or an arrow between the associated objects
May 25, 2013 COMSATS Intitute of Information Technology 137
138. Example – Binary Association
• Association “works-for” associates objects of exactly
two classes
May 25, 2013 COMSATS Intitute of Information Technology 138
Employee Company
works-for
1*
139. Example – Binary Association
• Association “drives” associates objects of exactly two
classes
May 25, 2013 COMSATS Intitute of Information Technology 139
Ali Car
drives
*1
140. Ternary Association
• Associates objects of exactly three classes
• Denoted by a diamond with lines connected to associated objects
May 25, 2013 COMSATS Intitute of Information Technology 140
141. Example – Ternary Association
• Objects of exactly three classes are associated
May 25, 2013 COMSATS Intitute of Information Technology 141
Student Teacher
Course
1
*
*
142. Example – Ternary Association
• Objects of exactly three classes are associated
May 25, 2013 COMSATS Intitute of Information Technology 142
Project Language
Person
*
1
*
143. N-ary Association
• An association between 3 or more classes
• Practical examples are very rare
May 25, 2013 COMSATS Intitute of Information Technology 143
144. Class diagram showing
association
• Association among classes is shown as a simple arrow (ray) in UML (Unified
Modeling 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 (bidirectional
association).
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” object
is known as Composition
• Composition is represented by a line with a filled-diamond head
towards the composer object
May 25, 2013 COMSATS Intitute of Information Technology 145
146. Class diagram showing
composition
May 25, 2013 COMSATS Intitute of Information Technology 146
Composition among classes is shown as solid diamond arrowhead in UML Class
Diagram.
147. Example – Composition of Ali
May 25, 2013 COMSATS Intitute of Information Technology 147
Ali
Body
Arm
Head
Leg
1
1
2 2
148. Example – Composition of Chair
May 25, 2013 COMSATS Intitute of Information Technology 148
Chair
SeatArm
Back
Leg
1
12 4
149. Composition is Stronger
• Composition is a stronger relationship, because
• Composed object becomes a part of the composer
• Composed object can’t exist independently
May 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 Ali
May 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 independently
May 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 is
called aggregation
• Aggregation is represented by a line with unfilled-diamond head
towards the container
May 25, 2013 COMSATS Intitute of Information Technology 154
154. Class diagram showing
aggregation
May 25, 2013 COMSATS Intitute of Information Technology 155
Aggregation among classes is shown as open diamond arrowhead in UML Class
Diagram.
155. Example – Aggregation
May 25, 2013 COMSATS Intitute of Information Technology 156
Room
Cupboard
Bed
Chair Table
*
1
1
1
157. Aggregation is Weaker
• Aggregation is weaker relationship, because
• Aggregate object is not a part of the container
• Aggregate object can exist independently
May 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 exist
independent of a particular room
May 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 independent
of a particular garden
May 25, 2013 COMSATS Intitute of Information Technology 160
160. More about „struct‟
• More on data hiding
• By default all the data members of struct are
accessible (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 from
anywhere, outside or inside.
• private: data or functions, cannot be accessed from
outside.
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 162
struct 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 164
struct TEST
{
private:
int x;
}
TEST var;
var.x = 10; //e
int y = var.x; //e
So even legitimate access of data goes through an interface!
We have secured the data further!!!
164. Member functions definition
May 25, 2013 National University of Computer and Emerging Sciences 165
struct 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 member
functions inside the
struct and define them
outside as well using the
name of struct to resolve
ambiguity.
• V. IMP: Note that this
allows us to separate
header and
implementation files!
165. Class Compatibility
• A class is behaviorally compatible with another if it supports all the
operations of the other class
• Such a class is called subtype
• A class can be replaced by its subtype
May 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 class
May 25, 2013 COMSATS Intitute of Information Technology 167
167. Example – Class Compatibility
May 25, 2013 COMSATS Intitute of Information Technology 168
Shape
color
vertices
move
setColor
draw
Circle
radius
draw
computeArea
Line
length
draw
getLength
Triangle
angle
draw
computeArea
168. Example – Class Compatibility
May 25, 2013 COMSATS Intitute of Information Technology 169
File
size
…
open
print
…
ASCII File
…
print
…
PDF File
…
print
…
PS File
…
print
…
169. Polymorphism
• In general, polymorphism refers to existence of different forms of a
single entity
• For example, both Diamond and Coal are different forms of Carbon
May 25, 2013 COMSATS Intitute of Information Technology 170
170. Polymorphism in OO Model
• In OO model, polymorphism means that different objects can behave
in different ways for the same message (stimulus)
• Consequently, sender of a message does not need to know exact class
of the receiver
May 25, 2013 COMSATS Intitute of Information Technology 171
171. Example – Polymorphism
May 25, 2013 COMSATS Intitute of Information Technology 172
Shape
Line Circle Triangle
draw
draw
draw draw
draw
View
172. Example – Polymorphism
May 25, 2013 COMSATS Intitute of Information Technology 173
File
ASCII File PDF File PS File
print
print
print print
print
Editor
173. Polymorphism – Advantages
• Messages can be interpreted in different ways
depending upon the receiver class
May 25, 2013 COMSATS Intitute of Information Technology 174
Shape
Line Circle Triangle
draw
draw
draw draw
draw
View
174. Polymorphism – Advantages
• New classes can be added without changing the existing
model
May 25, 2013 COMSATS Intitute of Information Technology 175
Square
draw
Shape
Line Circle Triangle
draw
draw
draw draw
draw
View
175. Polymorphism – Advantages
• In general, polymorphism is a powerful tool to develop flexible and
reusable systems
May 25, 2013 COMSATS Intitute of Information Technology 176
177. Problem Statement
• Develop a graphic editor that can draw different geometric shapes
such as line, circle and triangle. User can select, move or rotate a
shape. To do so, editor provides user with a menu listing different
commands. Individual shapes can be grouped together and can
behave 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 shapes
such as line, circle and triangle. User can select, move or rotate a
shape. To do so, editor provides user with a menu listing different
commands. Individual shapes can be grouped together and can
behave 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 boundary
May 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 single
shape”
• View – editor must have a display area
May 25, 2013 COMSATS Intitute of Information Technology 181
181. …Identify Classes
• Shape
• Line
• Circle
• Triangle
• Menu
May 25, 2013 COMSATS Intitute of Information Technology 182
• Group
• View
Following classes have been identified:
182. Object Model – Graphic Editor
May 25, 2013 COMSATS Intitute of Information Technology 183
Line
Circle
Triangle
GroupShape
View
Menu
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 Editor
May 25, 2013 COMSATS Intitute of Information Technology 187
TriangleCircleLine
ShapeView
nnnn
nn
nn
Menu
Group
nn
nnnn
nn
nn
187. Identify Attributes
Extract properties of the object
• From the problem statement
• Properties are not mentioned
May 25, 2013 COMSATS Intitute of Information Technology 188
188. …Identify Attributes
Extract properties of the object
• From the domain knowledge
May 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 knowledge
May 25, 2013 COMSATS Intitute of Information Technology 190
• Group
– noOfObjects
• View
– noOfObjects
– selected
• Menu
– Name
– isOpen
190. Object Model – Graphic Editor
May 25, 2013 COMSATS Intitute of Information Technology 191
Menu
name
isOpen
View
noOfObjects
selected
Shape
color
vertices
Line
length
Circle
radius
Group
noOfObjects
Triangle
angle
nn
n
nn
n
nn
n
n
n
n
nn
nn
n
191. Identify Operations
Extract verbs connected with an object
May 25, 2013 COMSATS Intitute of Information Technology 192
• Develop a graphic editor that can draw
different geometric shapes such as line,
circle and triangle. User can select, move
or rotate a shape. To do so, editor provides
user with a menu listing different
commands. Individual shapes can be
grouped together and can behave as a
single shape.
192. … Identify Operations
Eliminate irrelevant operations
• Develop – out of system boundary
• Behave – have broad semantics
May 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 knowledge
May 25, 2013 COMSATS Intitute of Information Technology 197
• View
– Add
– Remove
– Group
– Show
– Select
– Move
– Rotate
198. Identify Inheritance
Search “is a kind of” by looking at keywords like “such as”, “for
example”, etc
• “…shapes such as line, circle and triangle…”
– Line, Circle and Triangle inherits from Shape
May 25, 2013 COMSATS Intitute of Information Technology 199
199. …Identify Inheritance
By analyzing requirements
• “Individual shapes can be grouped together and can behave as a
single shape”
• Group inherits from Shape
May 25, 2013 COMSATS Intitute of Information Technology 200
200. Refining the Object Model
• Application of inheritance demands an iteration over the whole
object model
• In the inheritance hierarchy,
• All attributes are shared
• All associations are shared
• Some operations are shared
• Others are overridden
May 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 shapes
May 25, 2013 COMSATS Intitute of Information Technology 202
202. …Refining the Object Model
Share attributes
• Shape – Line, Circle, Triangle and Group
• Color, vertices
May 25, 2013 COMSATS Intitute of Information Technology 203
203. …Refining the Object Model
Share operations
• Shape – Line, Circle, Triangle and Group
• Select
• Move
• Rotate
May 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
• Draw
May 25, 2013 COMSATS Intitute of Information Technology 205
207. Class
• Class is a tool to realize objects
• Class is a tool for defining a new type
May 25, 2013 COMSATS Intitute of Information Technology 208
208. Example
• Lion is an object
• Student is an object
• Both has some attributes and some behaviors
May 25, 2013 COMSATS Intitute of Information Technology 209
209. Uses
• The problem becomes easy to understand
• Interactions can be easily modeled
May 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 software
May 25, 2013 COMSATS Intitute of Information Technology 211
211. Abstraction
• Only include details in the system that are required for making a
functional system
• Student
• Name
• Address
• Sibling
• Father Business
May 25, 2013 COMSATS Intitute of Information Technology 212
Relevant to our problem
Not relevant to our problem
212. Defining a New User Defined Type
class ClassName
{
…
DataType MemberVariable;
ReturnType MemberFunction();
…
};
May 25, 2013 COMSATS Intitute of Information Technology 213
Syntax
Syntax
213. Example
class 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 214
Member variables
MemberFunctions
214. Why Member Function
• They model the behaviors of an object
• Objects can make their data invisible
• Object remains in consistent state
May 25, 2013 COMSATS Intitute of Information Technology 215
216. Object and Class
• Object is an instantiation of a user defined type or a class
May 25, 2013 COMSATS Intitute of Information Technology 217
217. Declaring class variables
• Variables of classes (objects) are declared just like variables of
structures and built-in data types
TypeName 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 similar
fashion
May 25, 2013 COMSATS Intitute of Information Technology 219
219. Example
class Student{
int rollNo;
void setRollNo(int
aNo);
};
Student aStudent;
aStudent.rollNo;
May 25, 2013 COMSATS Intitute of Information Technology 220
Error
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 221
struct 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 & class
class TEST {
int x;
void Setx(int val) { x = val; };
int Getx() { return x; };
}
main() {
TEST var;
var.x = 10; //error
var.Setx(10); //error
int y = var.Getx(); //error
}
May 25, 2013 National University of Computer and Emerging Sciences 222
struct TEST {
int x;
void Setx(int val) { x = val; };
int Getx() { return x; };
}
main() {
TEST var;
var.x = 10; //possible
var.Setx(10);
int y = var.Getx();
}
• By default struct (C++) members are public,
whereas class members are private.
222. Diff. between struct & class
class TEST {
int x;
public:
void Setx(int val) { x = val; };
int Getx() { return x; };
}
main() {
TEST var;
var.x = 10; //error
var.Setx(10);
int y = var.Getx();
}
May 25, 2013 National University of Computer and Emerging Sciences 223
struct TEST {
private:
int x;
public:
void Setx(int val) { x = val; };
int Getx() { return x; };
}
main() {
TEST var;
var.x = 10; //error
var.Setx(10);
int y = var.Getx();
}
• By default struct (C++) members are public,
whereas class members are private.
224. Access specifiers
• There are three access specifiers
• ‘public’ is used to tell that member can be accessed whenever you have
access to the object
• ‘private’ is used to tell that member can only be accessed from a member
function
• ‘protected’ to be discussed when we cover inheritance
May 25, 2013 COMSATS Intitute of Information Technology 225
225. Example
class Student{
private:
char * name;
int rollNo;
public:
void setName(char *);
void setRollNo(int);
...
};
May 25, 2013 COMSATS Intitute of Information Technology 226
Cannot be accessed outside class
Can be
accessed
outside class
227. Default access specifiers
• When no access specifier is mentioned then by default the member is
considered private member
May 25, 2013 COMSATS Intitute of Information Technology 228
228. Example
class Student
{
char * name;
int RollNo;
};
class Student
{
private:
char * name;
int RollNo;
};
May 25, 2013 COMSATS Intitute of Information Technology 229
229. Example
class Student
{
char * name;
int RollNo;
void SetName(char *);
};
Student aStudent;
aStudent.SetName(Ali);
May 25, 2013 COMSATS Intitute of Information Technology 230
Error
230. Example
class 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 diagram
May 25, 2013 National University of Computer and Emerging Sciences 232 of 21
10..*
abstract
static
private
association
(“using”)
inheritance
(“is a”)
232. Assignment (CP)
• Install IBM Rational Rose or any other UML tool and draw the
diagrams used in this lecture and take a print out of those diagrams to
show me what you have done.
• Deadline: next class
May 25, 2013 COMSATS Intitute of Information Technology 233
233. References
• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (The
Waite 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
235. CSC241:
Object Oriented
Programming
Spring 2013
1. Inheritance Concepts
2. Polymorphism
May 25, 2013 COMSATS Intitute of Information Technology
236
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
237. Member Functions
• Member functions are the functions that operate on the data
encapsulated in the class
• Public member functions are the interface to the class
238. Member Functions (contd.)
• Define member function inside the class definition
OR
• Define member function outside the class definition
• But they must be declared inside class definition
239. Function Inside Class Body
class ClassName {
…
public:
ReturnType FunctionName() {
…
}
};
240. Example
•Define a class of student that has
a roll number. This class should
have a function that can be used
to set the roll number
242. Function Outside Class Body
class ClassName{
…
public:
ReturnType FunctionName();
};
ReturnType ClassName::FunctionName()
{
…
}
Scope
resolution
operator
244. Inline Functions
• Instead of calling an inline function compiler replaces the code at the
function call point
• Keyword ‘inline’ is used to request compiler to make a function inline
• It is a request and not a command
246. Inline Functions
• If we define the function inside the class body then the function is by
default an inline function
• In case function is defined outside the class body then we must use
the keyword ‘inline’ to make a function inline
252. Constructor
• Constructor is used to initialize the objects of a class
• Constructor is used to ensure that object is in well defined state at
the 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
256. Default Constructor
• Constructor without any argument is called default constructor
• If we do not define a default constructor the compiler will generate a
default constructor
• This compiler generated default constructor initialize the data
members to their default values
264. Example
Student::Student( char * aName = NULL,
int aRollNo= 0,
float aGPA = 0.0){
…
}
Is equivalent to
Student();
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 (The
Waite 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 a
software @ google
• When we need a software, the first place where we
go is at Google Search. If you don't know the
software name, then we use some keywords at
Google Search (for e.g. Note Taking software, Video
Editing software, Photo Editing software etc). Once
Google show us the results, we click the links after
reading its title and some description. Following such
practice often wastes our time by clicking useless
links. What most of the people don't know is that,
you can easily search for the software / applications
at Google Search using its filtering options. Let's see
how we can do that
• Consult the file uploaded
May 25, 2013 COMSATS Intitute of Information Technology 267
269. Revision
• Chapter 5 of book
May 25, 2013 COMSATS Intitute of Information Technology 270
270. Functions
May 25, 2013 COMSATS Intitute of Information Technology 271
A function groups a number of program statements into a unit
and 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 the
conceptual organization of a program
Another reason to use functions is to reduce program size. Any
sequence of instructions that appears in a program more than
once is a candidate for being made into a function.
The function’s code is stored in only one place in memory, even
though the function is executed many times in the course of the
program.
272. Functions
May 25, 2013 COMSATS Intitute of Information Technology 273
//demonstrates a simple function
#include <iostream>
using namespace std;
int cube(int x); // function deration
int 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 loop
system("PAUSE"); return 0;
}//end of main
int cube( int x ){ // function definition
return x*x*x; // returns cube of x:
} // { function body }
Input Arguments
Return type
273. Functions
May 25, 2013 COMSATS Intitute of Information Technology 274
Each integer read is passed to the cube() function by the call cube(n). The value
returned by the function replaces the expression cube(n) and then is passed to
the 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 means
that x is assigned the value of n when the function is called.
274. Default Arguments
May 25, 2013 COMSATS Intitute of Information Technology 275
#include <iostream>
using namespace std;
//declaration with default arguments
void repchar(char='*', int=45);
int main(){
repchar(); //prints 45 asterisks
repchar('='); //prints 45 equal signs
repchar('+', 30); //prints 30 plus signs
system("PAUSE"); return 0;
}
// displays line of characters
void repchar(char ch, int n){
// defaults supplied if necessary
for(int j=0; j<n; j++) // loops n times
cout << ch; // prints ch
cout << endl;
}
275. Inline Function
May 25, 2013 COMSATS Intitute of Information Technology 276
A function call involves substantial overhead.
Extra time and space have to be used to invoke
the function, pass parameters to it, allocate
storage for its local variables, store the
current variables and the location of execution
in the main program, etc.
In some cases, it is better to avoid all this
by specifying the function to be inline. This
tells the compiler to replace each call to the
function with explicit code for the function.
To the programmer, an inline function appears
the same as an ordinary function, except for
the use of the inline specifier.
276. Inline Function
May 25, 2013 COMSATS Intitute of Information Technology 277
// demonstrates inline functions
#include <iostream>
using namespace std;
inline float lbstokg(float pounds){
// converts pounds to kilograms
return 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. Recursion
May 25, 2013 COMSATS Intitute of Information Technology 278
The existence of functions makes possible a
programming technique called recursion.
Recursion involves a function calling
itself. This sounds rather improbable, and
indeed a function calling itself is often a
bug. However, when used correctly this
technique can be surprisingly powerful.
Recursion is much easier to understand with
an example than with lengthy explanations,
so let‟s apply it to a program:
The next program, uses recursion instead of
a loop to calculate factorial.
278. Recursion
May 25, 2013 COMSATS Intitute of Information Technology 279
#include <iostream>
using namespace std;
// calls itself to calculate factorials
unsigned 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 call
else
return 1;
}
int main(){
int n;
cout << "Enter an integer: "; cin >> n;
cout << "Factorial of " << n << " is " << fct(n) << "n";
system("PAUSE"); return 0;
}
280. References
• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (The
Waite Group). 4th ed. available in soft form.
May 25, 2013 COMSATS Intitute of Information Technology 281
284. Constructor
• Constructor is used to initialize the objects of a class
• Constructor is used to ensure that object is in well defined state at
the 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
288. Default Constructor
• Constructor without any argument is called default constructor
• If we do not define a default constructor the compiler will generate a
default constructor
• This compiler generated default constructor initialize the data
members to their default values
296. Example
Student::Student( char * aName = NULL,
int aRollNo= 0,
float aGPA = 0.0){
…
}
Is equivalent to
Student();
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
300. Shallow Copy
• When we initialize one object with another then the compiler copies
state of one object to the other
• This kind of copying is called shallow copying
303. References
• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (The
Waite 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
307. Destructor
• You might guess that another function is called
automatically when an object is destroyed. This is indeed
the case. Such a function is called a destructor.
• A destructor also has the same name as the class name
but 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-allocate
memory that was allocated for the object by the
constructor.
May 25, 2013 COMSATS Intitute of Information Technology 308
308. Using Destructor
May 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 Foo
system( "PAUSE" ); // Foo *s3; s3 = new Foo; delete s3;
return 0;
}
309. this Pointer
•There are situations where
designer wants to return
reference to current object from a
function
•In such cases reference is taken
from this pointer like (*this)
312. Separation of interface and
implementation
•Public member function exposed by a
class is called interface
•Separation of implementation from the
interface is good software engineering
313. Complex Number
•There are two representations of complex
number
• Euler form
• z = x + i y
• Phasor form
• z = |z| (cos + i sin )
• z is known as the complex modulus and is known as
the complex argument or phase
314. Example
float getX()
float getY()
void setNumber
(float i, float j)
…
float x
float y
Complex
Old implementation
float getX()
float getY()
void setNumber
(float i, float j)
…
float z
float theta
Complex
New implementation
317. Advantages
•User is only concerned about ways of accessing
data (interface)
•User has no concern about the internal
representation and implementation of the class
318. Separation of interface and
implementation
•Usually functions are defined in implementation
files (.cpp) while the class definition is given in
header file (.h)
•Some authors also consider this as separation of
interface and implementation
322. Classes, Objects and Memory
• you might have the impression that each object created
from a class contains separate copies of that class’s data
and 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 member
functions.
• The member functions are created and placed in memory
only once—when they are defined in the class definition.
• Since the functions for each object are identical. The data
items, 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 (The
Waite 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
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 characteristics
similar to a normal static variable: It is visible only
within the class, but its lifetime is the entire program.
• It continues to exist even if there are no objects of the
class.
• Why would we need a static member data?
May 25, 2013 COMSATS Intitute of Information Technology 328
328. static class member data
class 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 count
May 25, 2013 COMSATS Intitute of Information Technology 329
int main()
{
foo f1, f2, f3; //create three objects
cout << “count is “ << f1.getcount()
<< endl; //each object
cout << “count is “ << f2.getcount()
<< endl; //sees the
cout << “count is “ << f3.getcount()
<< endl; //same value
return 0;
}
329. static class member
• For multiple objects of the same class, new memory is
allocated for data members and shared memory for all
the functions.
• This shared memory is also used for static data
members.
• Static data member requires two separate statements
for:
• 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 it
actually was in early versions of C++), it would violate the
idea that a class definition is only a blueprint and does not
set aside any memory.
• Putting the definition of static member data outside the
class also serves to emphasize that the memory space for
such data is allocated only once, before the program starts
to execute,
• and that one static member variable is accessed by an
entire class; each object does not have its own version of
the variable, as it would with ordinary member data.
• In this way a static member variable is more like a global
variable.
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 is
not helpful about such errors.
• If you include the declaration of a static variable but forget its
definition, there will be no warning from the compiler.
• Everything looks fine until you get to the linker, which will tell
you that you’re trying to reference an undeclared global
variable.
• This happens even if you include the definition but forget the
class 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 of
a class/struct or class/struct name, you get the size of
the 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 in
class/struct
class 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 334
int sz = sizeof(Counter);
OR
Counter c1;
int sz = sizeof(c1);
Gives sz = 8
If 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 be
read only
•There must exist a mechanism to detect
error if such functions accidentally change
the data member
May 25, 2013 COMSATS Intitute of Information Technology 335
341. const Functions
•Constant member functions cannot modify the
state of any object
•They are just “read-only”
•Errors due to typing are also caught at compile
time
May 25, 2013 COMSATS Intitute of Information Technology 342
342. const Functions
•Constructors and Destructors cannot be const
•Constructor and destructor are used to modify
the object to a well defined state
May 25, 2013 COMSATS Intitute of Information Technology 343
344. const Function
•Constant member function cannot change
data member
•Constant member function cannot access
non-constant member functions
May 25, 2013 COMSATS Intitute of Information Technology 345
345. Example
class Student{
char * name;
public:
char *getName();
void setName(char * aName);
int ConstFunc() const{
name = getName();//error
setName(“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 (The
Waite 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
350. Arrays
In everyday life we commonly group similar
objects into units. We buy eggs by the carton.
In computer languages we also need to group
together data items of the same type. The most
basic mechanism that accomplishes this in C++
is the array.
Arrays can hold a few data items or tens of
thousands. The data items grouped in an array
can be simple types such as int or float, or
they can be user-defined types such as
structures and objects.
An array groups items of the same type. The
items in a in an array are accessed by an
index number. Using an index number to specify
an item allows easy access to a large number
of 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 ints
for(j=0; j<4; j++){ //get 4 ages
cout << "Enter an age: ";
cin >> age[j]; //access array element
}
for(j=0; j<4; j++){ //display 4 ages
cout << "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 from
array*/
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 array
cout << "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 elements
double a[SIZE]; // declares the array‟s elements as
type double
cout << "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); // declaration
int 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;
}
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 columns
get_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 pages
get_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 Algo
void 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] <<" ";
}