OOP COMPLETE NOTES
BY
Umer Tanvir
CSC241:
Object Oriented
Programming
Spring 2013
1. Starting OOP
May25,2013COMSATSInstituteofInformationTechnology
2
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
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
Procedural vs. Object-Oriented
• Procedural
Withdraw, deposit, transfer
• Object Oriented
Customer, money, account
May 25, 2013 COMSATS Institute of Information Technology 4
Object-Orientation
(OO)
May 25, 2013 COMSATS Institute of Information Technology 5
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
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
Examples – Model
• Highway maps
• Architectural models
• Mechanical models
May 25, 2013 COMSATS Institute of Information Technology 8
Example – OO Model
May 25, 2013 COMSATS Institute of Information Technology 9
…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
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
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
… What is an Object?
An object has
• State (attributes)
• Well-defined behaviour (operations)
• Unique identity
May 25, 2013 COMSATS Institute of Information Technology 13
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Example – Abstraction
• behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
May 25, 2013 COMSATS Institute of Information Technology 32
Student’s Perspective
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
Example – Abstraction
• behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
May 25, 2013 COMSATS Institute of Information Technology 34
Teacher’s Perspective
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
Example – Abstraction
May 25, 2013 COMSATS Institute of Information Technology 36
Driver’s View
Engineer’s View
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
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
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
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
Graphical Representation of Classes
May 25, 2013 COMSATS Institute of Information Technology 41
(Class Name)
(attributes)
(operations)
(Class Name)
Normal Form
Suppressed
Form
Example – Graphical Representation of
Classes
May 25, 2013 COMSATS Institute of Information Technology 42
Circle
center
radius
draw
computeArea
Normal Form
Suppressed
Form
Circle
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
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
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
Example – Inheritance
May 25, 2013 COMSATS Institute of Information Technology 46
Person
Teacher
DoctorStudent
Example – Inheritance
May 25, 2013 COMSATS Institute of Information Technology 47
Shape
Circle
TriangleLine
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
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
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
Inheritance – Advantages
• Reuse
• Less redundancy
• Increased maintainability
May 25, 2013 COMSATS Institute of Information Technology 51
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
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
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
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
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
Thanks
May 25, 2013 COMSATS Institute of Information Technology 57
CSC241:
Object Oriented
Programming
Spring 2013
1. Inheritance & Generalization
May25,2013COMSATSInstituteofInformationTechnology
58
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
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
Concepts Related with Inheritance
• Generalization
• Subtyping (extension)
• Specialization (restriction)
May 25, 2013 COMSATS Institute of Information Technology 60
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
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
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
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
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
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
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
Example –
Sub-typing
(Extension)
May 25, 2013 COMSATS Institute of Information Technology 68
Person
name
age
gender
eats
walks
Student
program
studyYear
study
takeExam
Example –
Sub-typing
(Extension)
May 25, 2013 COMSATS Institute of Information Technology 69
Shape
color
vertices
setColor
move
Circle
radius
computeCF
computeArea
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
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
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
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
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
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
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
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
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
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
Example – Abstract Classes
• Here, Vehicle is an abstract classMay 25, 2013 COMSATS Institute of Information Technology 80
Bus
TruckCar
Vehicle
color
model
accelerate
applyBrakes
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
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
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
Multiple Inheritance
• We may want to reuse characteristics of more than one parent class
May 25, 2013 COMSATS Institute of Information Technology 84
Example – Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 85
Mermaid
Example – Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 86
Mermaid
Woman Fish
Example – Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 87
Amphibious Vehicle
Example – Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 88
Amphibious Vehicle
Land Vehicle Water Vehicle
Vehicle
Car Boat
Problems with Multiple Inheritance
• Increased complexity
• Reduced understanding
• Duplicate features
May 25, 2013 COMSATS Institute of Information Technology 89
Problem – Duplicate Features
• Which eat operation Mermaid inherits?
May 25, 2013 COMSATS Institute of Information Technology 90
Mermaid
Woman Fish
eat
…
eat
…
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
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
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
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
Kinds of Association
• Class Association
• Inheritance
• Object Association
• Simple Association
• Composition
• Aggregation
May 25, 2013 COMSATS Institute of Information Technology 95
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
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
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
Example – Association
• Ali lives in a House
May 25, 2013 COMSATS Institute of Information Technology 99
Ali House
lives-in
11
Example – Association
• Ali drives his Car
May 25, 2013 COMSATS Institute of Information Technology 100
Ali Car
drives
*1
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
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*
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
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
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*
Example – Binary Association
• Association “drives” associates objects of exactly two
classes
May 25, 2013 COMSATS Institute of Information Technology 106
Ali Car
drives
*1
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
Example – Ternary Association
• Objects of exactly three classes are associated
May 25, 2013 COMSATS Institute of Information Technology 108
Student Teacher
Course
1
*
*
Example – Ternary Association
• Objects of exactly three classes are associated
May 25, 2013 COMSATS Institute of Information Technology 109
Project Language
Person
*
1
*
N-ary Association
• An association between 3 or more classes
• Practical examples are very rare
May 25, 2013 COMSATS Institute of Information Technology 110
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
Example – Composition of Ali
May 25, 2013 COMSATS Institute of Information Technology 112
Ali
Body
Arm
Head
Leg
1
1
2 2
Example – Composition of Chair
May 25, 2013 COMSATS Institute of Information Technology 113
Chair
SeatArm
Back
Leg
1
12 4
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
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
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
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
Example – Aggregation
May 25, 2013 COMSATS Institute of Information Technology 118
Room
Cupboard
Bed
Chair Table
*
1
1
1
Example – Aggregation
May 25, 2013 COMSATS Institute of Information Technology 119
Garden Plant*
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
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
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
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
Thanks
May 25, 2013 COMSATS Institute of Information Technology 124
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
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”.
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
Kinds of Association
• Class Association
• Inheritance
• Object Association
• Simple Association
• Composition
• Aggregation
May 25, 2013 COMSATS Intitute of Information Technology 128
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
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
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
Example – Association
• Ali lives in a House
May 25, 2013 COMSATS Intitute of Information Technology 132
Ali House
lives-in
11
Example – Association
• Ali drives his Car
May 25, 2013 COMSATS Intitute of Information Technology 133
Ali Car
drives
*1
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
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*
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
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
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*
Example – Binary Association
• Association “drives” associates objects of exactly two
classes
May 25, 2013 COMSATS Intitute of Information Technology 139
Ali Car
drives
*1
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
Example – Ternary Association
• Objects of exactly three classes are associated
May 25, 2013 COMSATS Intitute of Information Technology 141
Student Teacher
Course
1
*
*
Example – Ternary Association
• Objects of exactly three classes are associated
May 25, 2013 COMSATS Intitute of Information Technology 142
Project Language
Person
*
1
*
N-ary Association
• An association between 3 or more classes
• Practical examples are very rare
May 25, 2013 COMSATS Intitute of Information Technology 143
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
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
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.
Example – Composition of Ali
May 25, 2013 COMSATS Intitute of Information Technology 147
Ali
Body
Arm
Head
Leg
1
1
2 2
Example – Composition of Chair
May 25, 2013 COMSATS Intitute of Information Technology 148
Chair
SeatArm
Back
Leg
1
12 4
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
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
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
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
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
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.
Example – Aggregation
May 25, 2013 COMSATS Intitute of Information Technology 156
Room
Cupboard
Bed
Chair Table
*
1
1
1
Example – Aggregation
May 25, 2013 COMSATS Intitute of Information Technology 157
Garden Plant*
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
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
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
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
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
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
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!!!
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!
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
…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
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
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
…
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
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
Example – Polymorphism
May 25, 2013 COMSATS Intitute of Information Technology 172
Shape
Line Circle Triangle
draw
draw
draw draw
draw
View
Example – Polymorphism
May 25, 2013 COMSATS Intitute of Information Technology 173
File
ASCII File PDF File PS File
print
print
print print
print
Editor
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
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
Polymorphism – Advantages
• In general, polymorphism is a powerful tool to develop flexible and
reusable systems
May 25, 2013 COMSATS Intitute of Information Technology 176
Object-Oriented
Modeling
An Example
May 25, 2013 COMSATS Intitute of Information Technology 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
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
…Identify Classes
Eliminate irrelevant classes
• Editor – Very broad scope
• User – Out of system boundary
May 25, 2013 COMSATS Intitute of Information Technology 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
…Identify Classes
• Shape
• Line
• Circle
• Triangle
• Menu
May 25, 2013 COMSATS Intitute of Information Technology 182
• Group
• View
Following classes have been identified:
Object Model – Graphic Editor
May 25, 2013 COMSATS Intitute of Information Technology 183
Line
Circle
Triangle
GroupShape
View
Menu
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
… 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
… Identify Associations
Verify access paths
• Menu sends message to View
(Simple One-Way Association)
May 25, 2013 COMSATS Intitute of Information Technology 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
Identify Attributes
Extract properties of the object
• From the problem statement
• Properties are not mentioned
May 25, 2013 COMSATS Intitute of Information Technology 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
…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
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
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.
… Identify Operations
Eliminate irrelevant operations
• Develop – out of system boundary
• Behave – have broad semantics
May 25, 2013 COMSATS Intitute of Information Technology 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
…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
…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
…Identify Operations
Extract operations using domain knowledge
May 25, 2013 COMSATS Intitute of Information Technology 197
• View
– Add
– Remove
– Group
– Show
– Select
– Move
– Rotate
Group
noOfObjects
draw()
Triangle
angle
draw()
nn
Circle
radius
draw()
nn
Line
length
draw()
nn
Shape
color
vertices
draw()
select()
move()
rotate()
nn
View
noOfObjects
selected
add()
remove()
group()
show()
select()
move()
rotate()
nn
nn
nn
nn
Menu
name
isOpen
open()
select()
move()
rotate()
n
May 25, 2013 COMSATS Intitute of Information Technology 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
…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
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
…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
…Refining the Object Model
Share attributes
• Shape – Line, Circle, Triangle and Group
• Color, vertices
May 25, 2013 COMSATS Intitute of Information Technology 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
…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
Line
length
draw()
Circle
radius
draw()
Triangle
angle
draw()
Group
noOfObjects
draw()
Shape
color
vertices
draw()
select()
move()
rotate()
n
View
noOfObjects
selected
add()
remove()
group()
show()
select()
move()
rotate()
nn
Menu
name
isOpen
open()
select()
move()
rotate()
n
May 25, 2013 COMSATS Intitute of Information Technology 206
Group
noOfObjects
draw()
Triangle
angle
draw()
nn
Circle
radius
draw()
nn
Line
length
draw()
nn
Shape
color
vertices
draw()
select()
move()
rotate()
nn
View
noOfObjects
selected
add()
remove()
group()
show()
select()
move()
rotate()
nn
nn
nn
nn
Menu
name
isOpen
open()
select()
move()
rotate()
n
May 25, 2013 COMSATS Intitute of Information Technology 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
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
Uses
• The problem becomes easy to understand
• Interactions can be easily modeled
May 25, 2013 COMSATS Intitute of Information Technology 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
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
Defining a New User Defined Type
class ClassName
{
…
DataType MemberVariable;
ReturnType MemberFunction();
…
};
May 25, 2013 COMSATS Intitute of Information Technology 213
Syntax
Syntax
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
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
Example
Student aStudent;
aStudent.rollNo = 514;
aStudent.rollNo = -514; //Error
May 25, 2013 COMSATS Intitute of Information Technology 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
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
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
Example
class Student{
int rollNo;
void setRollNo(int
aNo);
};
Student aStudent;
aStudent.rollNo;
May 25, 2013 COMSATS Intitute of Information Technology 220
Error
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!
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.
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.
Access specifiers
May 25, 2013 COMSATS Intitute of Information Technology 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
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
Example
class Student{
...
int rollNo;
public:
void setRollNo(int aNo);
};
int main(){
Student aStudent;
aStudent.SetRollNo(1);
}
May 25, 2013 COMSATS Intitute of Information Technology 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
Example
class Student
{
char * name;
int RollNo;
};
class Student
{
private:
char * name;
int RollNo;
};
May 25, 2013 COMSATS Intitute of Information Technology 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
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
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”)
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
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
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 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
Review
• Class
• Concept
• Definition
• Data members
• Member Functions
• Access specifier
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
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
Function Inside Class Body
class ClassName {
…
public:
ReturnType FunctionName() {
…
}
};
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
Example
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){
rollNo = aRollNo;
}
};
Function Outside Class Body
class ClassName{
…
public:
ReturnType FunctionName();
};
ReturnType ClassName::FunctionName()
{
…
}
Scope
resolution
operator
Example
class Student{
…
int rollNo;
public:
void setRollNo(int aRollNo);
};
void Student::setRollNo(int aRollNo){
…
rollNo = aRollNo;
}
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
Example
inline int Area(int len, int hi)
{
return len * hi;
}
int main()
{
cout << Area(10,20);
}
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
Example
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){
…
rollNo = aRollNo;
}
};
Example
class Student{
…
public:
inline void setRollNo(int aRollNo);
};
void Student::setRollNo(int aRollNo){
…
rollNo = aRollNo;
}
Example
class Student{
…
public:
void setRollNo(int aRollNo);
};
inline void Student::setRollNo(int
aRollNo){
…
rollNo = aRollNo;
}
Example
class Student{
…
public:
inline void setRollNo(int aRollNo);
};
inline void Student::setRollNo(int
aRollNo){
…
rollNo = aRollNo;
}
Constructor
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
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
Example
class Student{
…
public:
Student(){
rollNo = 0;
…
}
};
Example
int main()
{
Student aStudent;
/*constructor is implicitly called at this
point*/
}
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
Example
class Student
{
int rollNo;
char *name;
float GPA;
public:
… //no constructors
};
Example
Compiler generated default constructor
{
rollNo = 0;
GPA = 0.0;
name = NULL;
}
Constructor Overloading
• Constructors can have parameters
• These parameters are used to initialize the data members with user
supplied data
Example
class Student{
…
public:
Student();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(int aRollNo, int aRollNo, float aGPA);
};
Example
Student::Student(int aRollNo,
char * aName){
if(aRollNo < 0){
rollNo = 0;
}
else {
rollNo = aRollNo;
}
…
}
Example
int main()
{
Student student1;
Student student2(“Name”);
Student student3(”Name”, 1);
Student student4(”Name”,1,4.0);
}
Constructor Overloading
• Use default parameter value to reduce the writing effort
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);
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
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
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 268
CSC241:
Object Oriented
Programming
Spring 2013
1. Functions
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
Revision
• Chapter 5 of book
May 25, 2013 COMSATS Intitute of Information Technology 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.
Return type
Input argumentsMay 25, 2013 COMSATS Intitute of Information Technology 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
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.
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;
}
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.
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;
}
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.
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;
}
Recursion
May 25, 2013 COMSATS Intitute of Information Technology 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
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 282
CSC241:
Object Oriented
Programming
Spring 2013
1. Constructors
May 25, 2013 COMSATS Intitute of Information Technology
283
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
Constructor
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
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
Example
class Student{
…
public:
Student(){
rollNo = 0;
…
}
};
Example
int main()
{
Student aStudent;
/*constructor is implicitly called at this
point*/
}
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
Example
class Student
{
int rollNo;
char *name;
float GPA;
public:
… //no constructors
};
Example
Compiler generated default constructor
{
rollNo = 0;
GPA = 0.0;
name = NULL;
}
Constructor Overloading
• Constructors can have parameters
• These parameters are used to initialize the data members with user
supplied data
Example
class Student{
…
public:
Student();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(char * aName, int aRollNo, float aGPA);
};
Example
Student::Student(int aRollNo,
char * aName){
if(aRollNo < 0){
rollNo = 0;
}
else {
rollNo = aRollNo;
}
…
}
Example
int main()
{
Student student1;
Student student2(“Name”);
Student student3(”Name”, 1);
Student student4(”Name”,1,4.0);
}
Constructor Overloading
• Use default parameter value to reduce the writing effort
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);
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
Example
void func1(Student student){
…
}
int main(){
Student studentA;
Student studentB = studentA;
func1(studentA);
}
Copy Constructor (Syntax)
Student::Student(
const Student &obj){
rollNo = obj.rollNo;
name = obj.name;
GPA = obj.GPA;
}
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
Example
Student studentA;
Student studentB = studentA;
Name
GPA
RollNo
studentA
Name
GPA
RollNo
studentB
A
H
M
A
D
…
Memory
Assignment
• Lab Assignment No 3
May 25, 2013 COMSATS Intitute of Information Technology 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
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 305
CSC241:
Object Oriented
Programming
Spring 2013
1. Destructor
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
Review
•Copy constructors
•Destructor
•this Pointer
•Separation of interface and
implementation
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
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;
}
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)
Example
Student Student::setRollNo(int aNo)
{
…
return *this;
}
Student Student::setName(char *aName)
{
…
return *this;
}
Example
int main()
{
Student aStudent;
Student bStudent;
bStudent = aStudent.setName(“Ahmad”);
…
bStudent = aStudent.setName(“Ali”).setRollNo(2);
return 0;
}
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
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
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
Example
class Complex{ //old
float x;
float y;
public:
void setNumber(float i, float j){
x = i;
y = j;
}
…
};
Example
class Complex{ //new
float z;
float theta;
public:
void setNumber(float i, float j){
theta = arctan(j/i);
…
}
…
};
Advantages
•User is only concerned about ways of accessing
data (interface)
•User has no concern about the internal
representation and implementation of the class
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
Student.h
class Student{
int rollNo;
public:
void setRollNo(int aRollNo);
int getRollNo();
…
};
Student.cpp
#include “student.h”
void Student::setRollNo(int aNo){
…
}
int Student::getRollNo(){
…
}
Driver.cpp
#include “student.h”
int main(){
Student aStudent;
}
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
May 25, 2013 COMSATS Intitute of Information Technology 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
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 326
CSC241:
Object Oriented
Programming
Spring 2013
1. Static class member
2. Const member function
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
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
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;
}
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
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
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
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
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.
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
Example
bool Student::isRollNo(int aNo){
if(rollNo = = aNo){
return true;
}
return false;
}
May 25, 2013 COMSATS Intitute of Information Technology 336
Example
bool Student::isRollNo(int aNo){
/*undetected typing mistake*/
if(rollNo = aNo){
return true;
}
return false;
}
May 25, 2013 COMSATS Intitute of Information Technology 337
Example
bool Student::isRollNo
(int aNo)const{
/*compiler error*/
if(rollNo = aNo){
return true;
}
return false;
}
May 25, 2013 COMSATS Intitute of Information Technology 338
const Member Functions
•Keyword const is placed at the end of the
parameter list
May 25, 2013 COMSATS Intitute of Information Technology 339
const Member Functions
Declaration:
class ClassName{
ReturnVal Function() const;
};
Definition:
ReturnVal ClassName::Function() const{
…
}
May 25, 2013 COMSATS Intitute of Information Technology 340
Example
class Student{
public:
int getRollNo() const {
return rollNo;
}
};
May 25, 2013 COMSATS Intitute of Information Technology 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
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
Example
class Time{
public:
Time() const {} //error…
~Time() const {} //error…
};
May 25, 2013 COMSATS Intitute of Information Technology 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
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
May 25, 2013 COMSATS Intitute of Information Technology 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
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 349
CSC241:
Object Oriented
Programming
Spring 2013
1. Arrays & String (Chapter
7)
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
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.
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
n Dimensional Arrays
0x22ff40 = 11
0x22ff44 = 12
0x22ff48 = 13
0x22ff4C = 21
0x22ff50 = 22
0x22ff54 = 23
ary[0][0]=
ary[0][1]=
ary[0][2]=
ary[1][0]=
ary[1][1]=
ary[1][2]=






232221
131211
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;
}
3-Dimensional Arrays
0x22ff30 = 11
0x22ff34 = 12
0x22ff38 = 13
0x22ff3C = 21
0x22ff40 = 22
0x22ff44 = 23
ary[0][0]=
ary[0][1]=
ary[0][2]=
ary[1][0]=
ary[1][1]=
ary[1][2]=
0x22ff48 = 31
0x22ff4C = 32
0x22ff50 = 33
ary[2][0]=
ary[2][1]=
ary[2][2]=










333231
232221
131211
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;
}
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;
}
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
}
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;
}
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;
}
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] <<" ";
}
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;
}
Reading Embedded Blanks
// blanksin.cpp reads string with embedded blanks
#include <iostream>
using namespace std;
int main(){
const int MAX = 80; // max characters in string
char str[MAX]; // string variable str
cout << "nEnter a string: ";
// cin.get() means a member function get() of the stream
// class of which cin is an object
cin.get(str, MAX); // put string in str
// first argument to get() is the array address where
the
// string being input will be placed.
// The second argument specifies the maximum size of the
// array
cout << "You entered: " << str << endl;
return 0;
}
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 string
char str1[] = "Oh, Captain, my Captain! "
"our fearful trip is done";
const int MAX = 80; int j; // MAX is size of str2 buffer
char str2[MAX]; //empty string
for( j=0; j<strlen(str1); j++) //copy strlen characters
str2[j] = str1[j]; // from str1 to str2
str2[j] = '0'; //insert NULL at end
cout << str2 << endl; //display str2
system("PAUSE"); return 0;
}
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 buffer
char str2[MAX]; //empty string
strcpy(str2, str1); //copy str1 to str2
cout << str2 << endl; //display str2
system("PAUSE"); return 0;
}
Array of Strings
// straray.cpp
// array of strings
#include <iostream>
using namespace std;
int main(){
const int DAYS = 7; //number of strings in array
const int MAX = 10; //maximum size of each string
//An array of strings
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday" , "Saturday" };
for( int j=0 ; j<DAYS ; j++) //display every string
cout << star[j] << endl;
system("PAUSE");
return 0;
}
Array of Strings
Lab Task
Write a and test a program to calculate Determinant and Reverse of a 3x3 matrix
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 376
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 377
CSC241:
Object Oriented
Programming
Spring 2013
1. Composition
2. Aggregation
3. Friend Functions
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
Pointer to Objects
• Pointer to objects are similar as pointer to built-in types
• They can also be used to dynamically allocate objects
Example
class Student{
…
public:
Studen();
Student(char * aName);
void setRollNo(int aNo);
};
Example (Aggregation)
int main(){
Student obj;
Student *ptr;
ptr = &obj;
ptr->setRollNo(10);
return 0;
}
Allocation with new Operator
• new operator can be used to create objects at runtime
Example
int main(){
Student *ptr;
ptr = new Student;
ptr->setRollNo(10);
return 0;
}
Example
int main(){
Student *ptr;
ptr = new Student(“Ali”);
ptr->setRollNo(10);
return 0;
}
Breakup of new Operation
• new operator is decomposed as follows
• Allocating space in memory
• Calling the appropriate constructor
Case Study
Design a class date through which user must be able to perform
following operations
• Get and set current day, month and year
• Increment by x number of days, months and year
• Set default date
Attributes
• Attributes that can be seen in this problem statement are
• Day
• Month
• Year
• Default date
Attributes
• The default date is a feature shared by all objects
• This attribute must be declared a static member
Attributes in Date.h
class Date
{
int day;
int month;
int year;
static Date defaultDate;
…
};
Interfaces
• getDay
• getMonth
• getYear
• setDay
• setMonth
• setYear
• addDay
• addMonth
• addYear
• setDefaultDate
Interfaces
• As the default date is a static member the interface setDefaultDate
should also be declared static
Interfaces in Date.h
class Date{
…
public:
void setDay(int aDay);
int getDay() const;
void addDay(int x);
…
…
};
Interfaces in Date.h
class Date{
…
public:
static void setDefaultDate(
int aDay,int aMonth, int aYear);
…
};
Constructors and Destructors in Date.h
Date(int aDay = 0,
int aMonth= 0, int aYear= 0);
~Date(); //Destructor
};
Implementation of Date Class
• The static member variables must be initialized
Date Date::defaultDate (07,3,2013);
Constructors
Date::Date(int aDay, int aMonth,
int aYear) {
if(aDay==0) {
this->day = defaultDate.day;
}
else{
setDay(aDay);
}
//similarly for other members
}
Destructor
• We are not required to do any house keeping chores in destructor
Date::~Date
{
}
Getter and Setter
void Date::setMonth(int a){
if(a > 0 && a <= 12){
month = a;
}
int getMonth() const{
return month;
}
addYear
void Date::addYear(int x){
year += x;
if(day == 29 && month == 2
&& !leapyear(year)){
day = 1;
month = 3;
}
}
Helper Function
class Date{
…
private:
bool leapYear(int x) const;
…
};
Helper Function
bool Date::leapYear(int x) const{
if((x%4 == 0 && x%100 != 0)
|| (x%400==0)){
return true;
}
return false;
}
setDefaultDate
void Date::setDefaultDate(
int d, int m, int y){
if(d >= 0 && d <= 31){
day = d;
}
…
}
Aggregation
Composition vs. Aggregation
►Aggregation is a weak relationship
Room(char *, int)
~Room()
FoldChair(int) : bool
…
Chair()
DoSomething() : void
FoldChair() : bool
UnFoldChair() : bool
~Chair()
…
area : float
chairs[50]:Chair *
Room
…
Chair
Aggregation
►In aggregation, a pointer or reference to an object is
created inside a class
►The sub-object has a life that is NOTdependant
on 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 may
not be destroyed
Aggregation
class Room{
private:
float area;
Chair * chairs[50];
Public:
Room();
void AddChair(Chair *, int chairNo);
Chair * GetChair(int chairNo);
bool FoldChair(int chairNo);
…
};
Aggregation
Room::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;
}
Aggregation
Chair * Room::GetChair(int chairNo){
if(chairNo >= 0 && chairNo < 50)
return chairs[chairNo];
else
return NULL;
}
bool Room::FoldChair(int chairNo){
if(chairNo >= 0 && chairNo < 50)
return chairs[chairNo]->FoldChair();
else
return false;
}
Aggregationint main(){
Chair ch1;
{
Room r1;
r1.AddChair(&ch1, 1);
r1.FoldChair(1);
}
ch1.UnFoldChair(1);
return 0;
}
Friend Functions►Consider the following class:
class X{
private:
int a, b;
public:
void MemberFunction();
…
}
Friend Functions►Global function:
void DoSomething(X obj){
obj.a = 3; //Error
obj.b = 4; //Error
}
Friend Functions►In order to access the member variables of the class, function
definition 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 members
of class X
Friend Functions
►Prototypes of friend functions
appear in the class definition
►But friend functions are NOT
member functions
Friend Functions
►Friend functions can be placed anywhere in the class
without any effect
►Access specifiers don’t affect friend functions or
classes
class X{
...
private:
friend void DoSomething(X);
public:
friend void DoAnything(X);
...
};
Friend Functions
►While the definition of the friend function is:
void DoSomething(X obj){
obj.a = 3; // No Error
obj.b = 4; // No Error
…
}
►friend keyword is not given in definition
Friend Functions
►If keyword friend is used in the function
definition, it’s a syntax error
//Error…
friend void DoSomething(X obj){
…
}
Friend Classes
•Similarly, one class can also be made friend of
another class:
class X{
friend class Y;
…
};
•Member functions of class Y can access
private data members of class X
Friend Classes
•Example:
class X{
friend class Y;
private:
int x_var1, x_var2;
...
};
Friend Classes
class Y{
private:
int y_var1, y_var2;
X objX;
public:
void setX(){
objX.x_var1 = 1;
}
};
Friend Classes
int main(){
Y objY;
objY.setX();
return 0;
}
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 420
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 421
CSC241:
Object Oriented
Programming
Spring 2013
1. Operator Overloading
May25,2013
COMSATSIntituteofInformation
Technology
422
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
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,2013
COMSATSIntituteofInformation
Technology
423
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,2013
COMSATSIntituteofInformation
Technology
424
Operator overloading
►The following statement:
Complex c3 = c1.Add(c2);
Adds the contents of c2 to c1 and assigns
it to c3 (copy constructor)
May25,2013
COMSATSIntituteofInformation
Technology
425
Operator overloading
►To perform operations in a single
mathematical statement e.g:
c1+c2+c3+c4
►We have to explicitly write:
►c1.Add(c2.Add(c3.Add(c4)))
May25,2013
COMSATSIntituteofInformation
Technology
426
Operator overloading
►Alternative way is:
► t1 = c3.Add(c4);
► t2 = c2.Add(t1);
► t3 = c1.Add(t2);
May25,2013
COMSATSIntituteofInformation
Technology
427
Operator overloading
►If the mathematical expression is big:
• Converting it to C++ code will involve
complicated mixture of function calls
• Less readable
• Chances of human mistakes are very high
• Code produced is very hard to maintain
May25,2013
COMSATSIntituteofInformation
Technology
428
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 explicitly
converted into function calls
May25,2013
COMSATSIntituteofInformation
Technology
429
Operator overloading
►Assume that operator + has been
overloaded
►Actual C++ code becomes:
c1+c2+c3+c4
►The resultant code is very easy to read,
write and maintain
May25,2013
COMSATSIntituteofInformation
Technology
430
Operator overloading
►C++ automatically overloads operators for
pre-defined types
►Example of predefined types:
int
float
double
char
long
May25,2013
COMSATSIntituteofInformation
Technology
431
Operator overloading
►Example:
float x;
int y;
x = 102.02 + 0.09;
Y = 50 + 47;
May25,2013
COMSATSIntituteofInformation
Technology
432
Operator overloading
►The compiler probably calls the correct
overloaded low level function for addition i.e:
// for integer addition:
Add(int a, int b)
// for float addition:
Add(float a, float b)
May25,2013
COMSATSIntituteofInformation
Technology
433
Operator overloading
►Operator functions are not usually called
directly
►They are automatically invoked to evaluate
the operations they implement
May25,2013
COMSATSIntituteofInformation
Technology
434
Operator overloading
►List of operators that can be
overloaded in C++:
May25,2013
COMSATSIntituteofInformation
Technology
435
Operator overloading
►List of operators that can’t be
overloaded:
►Reason: They take name, rather than
value in their argument except for ?:
►?: is the only ternary operator in C++
and can’t be overloaded
May25,2013
COMSATSIntituteofInformation
Technology
436
Operator overloading
►The precedence of an operator is NOT
affected due to overloading
►Example:
c1*c2+c3
c3+c2*c1
both yield the same answer
May25,2013
COMSATSIntituteofInformation
Technology
437
Operator overloading
►Associativity is NOT changed
due to overloading
►Following arithmetic
expression always is evaluated
from left to right:
c1 + c2 + c3 + c4
May25,2013
COMSATSIntituteofInformation
Technology
438
Operator overloading
►Unary operators and assignment
operator are right associative, e.g:
a=b=c is same as a=(b=c)
►All other operators are left
associative:
c1+c2+c3 is same as
(c1+c2)+c3
May25,2013
COMSATSIntituteofInformation
Technology
439
Operator overloading
►Always write code representing
the operator
►Example:
Adding subtraction code
inside the + operator
will create chaos
May25,2013
COMSATSIntituteofInformation
Technology
440
Operator overloading
►Creating a new operator is a
syntax error (whether unary, binary
or ternary)
► You cannot create $
May25,2013
COMSATSIntituteofInformation
Technology
441
Operator overloading
►Arity of an operator is NOT affected by
overloading
►Example:
Division operator will take
exactly two operands in any
case:
b = c / d
May25,2013
COMSATSIntituteofInformation
Technology
442
Binary operators
►Binary operators act on two quantities
►Binary operators:
May25,2013
COMSATSIntituteofInformation
Technology
443
Binary operators
►General syntax:
Member function:
TYPE1 CLASS::operator B_OP(
TYPE2 rhs){
...
}
May25,2013
COMSATSIntituteofInformation
Technology
444
Binary operators
►General syntax:
Non-member function:
TYPE1 operator B_OP(TYPE2 lhs,
TYPE3 rhs){
...
}
May25,2013
COMSATSIntituteofInformation
Technology
445
Binary operators
►The “operator OP” must have at least
one formal parameter of type class (user
defined type)
►Following is an error:
int operator + (int, int);
May25,2013
COMSATSIntituteofInformation
Technology
446
Binary operators
►Overloading + operator:
class Complex{
private:
double real, img;
public:
…
Complex operator +(const
Complex & rhs);
};
May25,2013
COMSATSIntituteofInformation
Technology
447
Binary operators
Complex Complex::operator +(
const Complex & rhs){
Complex t;
t.real = real + rhs.real;
t.img = img + rhs.img;
return t;
}
May25,2013
COMSATSIntituteofInformation
Technology
448
Binary operators
►The return type is Complex so as to facilitate complex
statements like:
Complex t = c1 + c2 + c3;
►The above statement is automatically converted by
the compiler into appropriate function calls:
(c1.operator +(c2)).operator +(c3);
May25,2013
COMSATSIntituteofInformation
Technology
449
Binary operators
►If the return type was void,
class Complex{
...
► public:
► void operator+(
► const Complex & rhs);
};
May25,2013
COMSATSIntituteofInformation
Technology
450
Binary operators
void Complex::operator+(const
Complex & rhs){
real = real + rhs.real;
img = img + rhs.img;
};
May25,2013
COMSATSIntituteofInformation
Technology
451
Binary operators
►we have to do the same operation c1+c2+c3 as:
c1+c2
c1+c3
// final result is stored in c1
May25,2013
COMSATSIntituteofInformation
Technology
452
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 maintain
May25,2013
COMSATSIntituteofInformation
Technology
453
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 454
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 455
CSC241:
Object Oriented
Programming
Spring 2013
1. Inheritance
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
Inheritance in Classes
• If a class B inherits from class A, then B contains all
the characteristics (information structure and
behavior) 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 Intitute of Information Technology 457
UML Notation
May 25, 2013 COMSATS Intitute of Information Technology 458
Parent Class
Child Class
Base Class
Derived Class
Inheritance in C++
• There are three types of inheritance in C++
• Public
• Private
• Protected
May 25, 2013 COMSATS Intitute of Information Technology 459
“IS A” Relationship
• IS A relationship is modeled with the help of public
inheritance
• Syntax
class ChildClass
: public BaseClass{
...
};
May 25, 2013 COMSATS Intitute of Information Technology 460
Example
class Person{
...
};
class Student: public Person{
...
};
May 25, 2013 COMSATS Intitute of Information Technology 461
Accessing Members
• Public members of base class become public member
of derived class
• Private members of base class are not accessible from
outside of base class, even in the derived class
(Information Hiding)
May 25, 2013 COMSATS Intitute of Information Technology 462
Example
class Person{
char *name;
int age;
...
public:
const char *GetName() const;
int GetAge() const;
...
};
May 25, 2013 COMSATS Intitute of Information Technology 463
Example
class 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
Example
void Student::Print()
{
cout << name << “ is in” << “ semester
” << semester;
}
May 25, 2013 COMSATS Intitute of Information Technology 465
ERROR
Example
void Student::Print()
{
cout << GetName()
<< “ is in semester ”
<< semester;
}
May 25, 2013 COMSATS Intitute of Information Technology 466
Example
int main(){
Student stdt;
stdt.semester = 0;//error
stdt.name = NULL; //error
cout << stdt.GetSemester();
cout << stdt.GetName();
return 0;
}
May 25, 2013 COMSATS Intitute of Information Technology 467
Allocation in Memory
• The object of derived class is represented in memory
as follows
May 25, 2013 COMSATS Intitute of Information Technology 468
Data members of base
class
Data members of
derived class
base member1
base member2
...
derived member1
derived member2
...
Allocation in Memory
• Every object of derived class has an anonymous
object of base class
May 25, 2013 COMSATS Intitute of Information Technology 469
Constructors
• The anonymous object of base class must be
initialized using constructor of base class
• When a derived class object is created the
constructor of base class is executed before the
constructor of derived class
May 25, 2013 COMSATS Intitute of Information Technology 470
Constructors
May 25, 2013 COMSATS Intitute of Information Technology 471
Base class constructor
initializes the anonymous
object
Derived class constructor
initializes the derived class
object
base member1
base member2
...
derived member1
derived member2
...
Example
class Parent{
public:
Parent(){ cout <<
“Parent Constructor...”;}
};
class Child : public Parent{
public:
Child(){ cout <<
“Child Constructor...”;}
};
May 25, 2013 COMSATS Intitute of Information Technology 472
Example
int main(){
Child cobj;
return 0;
}
May 25, 2013 COMSATS Intitute of Information Technology 473
Output:
Parent Constructor...
Child Constructor...
Constructor
• If default constructor of base class does not exist then
the compiler will try to generate a default constructor
for base class and execute it before executing
constructor of derived class
May 25, 2013 COMSATS Intitute of Information Technology 474
Constructor
•If the user has given only an overloaded
constructor for base class, the compiler
will not generate default constructor for
base class
May 25, 2013 COMSATS Intitute of Information Technology 475
Example
class Parent{
public:
Parent(int i){}
};
class Child : public Parent{
public:
Child(){}
} Child_Object; //ERROR
May 25, 2013 COMSATS Intitute of Information Technology 476
Base Class Initializer
• C++ has provided a mechanism to explicitly call a
constructor of base class from derived class
• The syntax is similar to member initializer and is
referred as base-class initialization
May 25, 2013 COMSATS Intitute of Information Technology 477
Example
class Parent{
public:
Parent(int i){…};
};
class Child : public Parent{
public:
Child(int i): Parent(i)
{…}
};
May 25, 2013 COMSATS Intitute of Information Technology 478
Example
class 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
Base Class Initializer
• User can provide base class initializer and
member initializer simultaneously
May 25, 2013 COMSATS Intitute of Information Technology 480
Example
class Parent{
public:
Parent(){…}
};
class Child : public Parent{
int member;
public:
Child():member(0), Parent()
{…}
};
May 25, 2013 COMSATS Intitute of Information Technology 481
Base Class Initializer
• The base class initializer can be written after
member initializer for derived class
• The base class constructor is executed before
the initialization of data members of derived
class.
May 25, 2013 COMSATS Intitute of Information Technology 482
Initializing Members
• Derived class can only initialize members of base class
using overloaded constructors
• Derived class can not initialize the public data
member of base class using member initialization
list
May 25, 2013 COMSATS Intitute of Information Technology 483
Example
class Person{
public:
int age;
char *name;
...
public:
Person();
};
May 25, 2013 COMSATS Intitute of Information Technology 484
Example
class Student: public Person{
private:
int semester;
...
public:
Student(int a):age(a)
{ //error
}
};
May 25, 2013 COMSATS Intitute of Information Technology 485
Reason
• It will be an assignment not an initialization
May 25, 2013 COMSATS Intitute of Information Technology 486
Destructors
• Destructors are called in reverse order of constructor
called
• Derived class destructor is called before the base class
destructor is called
May 25, 2013 COMSATS Intitute of Information Technology 487
Example
class 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
Example
Output:
Parent Constructor
Child Constructor
Child Destructor
Parent Destructor
May 25, 2013 COMSATS Intitute of Information Technology 489
Protected Access Specifier
May 25, 2013 COMSATS Intitute of Information Technology 490
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);
Date Class
...
private:
bool IsLeapYear();
};
int main(){
Date aDate;
aDate.IsLeapYear(); //Error
return 0;
}
Creating SpecialDate Class
Special Date
Date Special Date
AddSpecialYear
...
Creating SpecialDate Class
class SpecialDate: public Date{
…
public:
void AddSpecialYear(int i){
...
if(day == 29 && month == 2
&& !IsLeapyear(year+i)){ //ERROR!
...
}
}
};
Modify Access Specifier
• We can modify access specifier “IsLeapYear” from private to public
Modified Date Class
class Date{
public:
...
bool IsLeapYear();
};
Modified AddSpecialYear
void SpecialDate :: AddSpecialYear
(int i){
...
if(day == 29 && month == 2
&& !IsLeapyear(year+i)){
...
}
}
Protected members
• Protected members can not be accessed outside the class
• Protected members of base class become protected member of
derived class in Public inheritance
Modified Date Class
class Date{
…
protected:
bool IsLeapYear();
};
int main(){
Date aDate;
aDate.IsLeapYear(); //Error
return 0;
}
Modified AddSpecialYear
void SpecialDate :: AddSpecialYear
(int i){
...
if(day == 29 && month == 2
&& !IsLeapyear(year+i)){
...
}
}
Disadvantages
• Breaks encapsulation
• The protected member is part of base class’s
implementation as well as derived class’s implementation
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 ,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
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 503
CSC241:
Object Oriented
Programming
Spring 2013
1. Inheritance
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
Hierarchy of Inheritance
• We represent the classes involved in inheritance
relation in tree like hierarchy
May 25, 2013 COMSATS Intitute of Information Technology 505
Example
May 25, 2013 COMSATS Intitute of Information Technology 506
GrandParent
Parent1 Parent2
Child1 Child2
Direct Base Class
•A direct base class is explicitly listed in a
derived class's header with a colon (:)
class Child1:public Parent1
...
May 25, 2013 COMSATS Intitute of Information Technology 507
Indirect Base Class
•An indirect base class is not explicitly listed
in a derived class's header with a colon (:)
•It is inherited from two or more levels up
the hierarchy of inheritance
class GrandParent{};
class Parent1:
public GrandParent {};
class Child1:public Parent1{};
May 25, 2013 COMSATS Intitute of Information Technology 508
Base Initialization
• The child can only perform the initialization of direct base class
through base class initialization list
• The child can not perform the initialization of an indirect base class
through base class initialization list
May 25, 2013 COMSATS Intitute of Information Technology 509
Example
class GrandParent{
int gpData;
public:
GrandParent() : gpData(0){...}
GrandParent(int i) : gpData(i){...}
void Print() const;
};
May 25, 2013 COMSATS Intitute of Information Technology 510
Example
class Parent1: public GrandParent{
int pData;
public:
Parent1() : GrandParent(), pData(0) {…}
};
May 25, 2013 COMSATS Intitute of Information Technology 511
Example
class Child1 : public Parent1 {
public:
Child1() : Parent1() {...}
Child1(int i) : GrandParent (i) //Error
{...}
void Print() const;
};
May 25, 2013 COMSATS Intitute of Information Technology 512
Overriding
• Child class can override the function of GrandParent class
May 25, 2013 COMSATS Intitute of Information Technology 513
Example
May 25, 2013 COMSATS Intitute of Information Technology 514
GrandParent
Print()
Parent1
Child1
Print()
Example
void GrandParent::Print() {
cout << “GrandParent::Print”
<< endl;
}
void Child1::Print() {
cout << “Child1::Print” << endl;
}
May 25, 2013 COMSATS Intitute of Information Technology 515
Example
int main(){
Child1 obj;
obj.Print();
obj.Parent1::Print();
obj.GrandParent::Print();
return 0;
}
May 25, 2013 COMSATS Intitute of Information Technology 516
Output
• Output is as follows
Child1::Print
GrandParent::Print
GrandParent::Print
May 25, 2013 COMSATS Intitute of Information Technology 517
Types of Inheritance
• There are three types of inheritance
• Public
• Protected
• Private
• Use keyword public, private or protected to specify
the type of inheritance
May 25, 2013 COMSATS Intitute of Information Technology 518
Public Inheritance
Member access in
Base Class Derived Class
Public Public
Protected Protected
Private Hidden
class Child: public Parent {…};
Protected Inheritance
Member access in
Base Class Derived Class
Public Protected
Protected Protected
Private Hidden
class Child: protected Parent {…};
Private Inheritance
Member access in
Base Class Derived Class
Public Private
Protected Private
Private Hidden
class Child: private Parent {…};
Private Inheritance
• If the user does not specifies the type of inheritance then the default
type is private inheritance
class Child: private Parent {…}
is equivalent to
class Child: Parent {…}
May 25, 2013 COMSATS Intitute of Information Technology 522
Private Inheritance
• We use private inheritance when we want to reuse code of some
class
• Private Inheritance is used to model “Implemented in terms of”
relationship
May 25, 2013 COMSATS Intitute of Information Technology 523
Example
class Collection {
...
public:
void AddElement(int);
bool SearchElement(int);
bool SearchElementAgain(int);
bool DeleteElement(int);
};
May 25, 2013 COMSATS Intitute of Information Technology 524
Example
• If element is not found in the Collection the function SearchElement
will return false
• SearchElementAgain finds the second instance of element in the
collection
May 25, 2013 COMSATS Intitute of Information Technology 525
Class Set
class Set: private Collection {
private:
...
public:
void AddMember(int);
bool IsMember(int);
bool DeleteMember(int);
};
May 25, 2013 COMSATS Intitute of Information Technology 526
Class Set
void 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
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 ,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
Thanks
May 25, 2013 COMSATS Intitute of Information Technology 529
CSC241:
Object Oriented
Programming
Spring 2013
1. Private Inheritance
2. Specialization
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
Private Inheritance
• If the user does not specifies the type of inheritance then the default
type is private inheritance
class Child: private Parent {…}
is equivalent to
class Child: Parent {…}
May 25, 2013 COMSATS Intitute of Information Technology
Private Inheritance
• We use private inheritance when we want to reuse code of some
class
• Private Inheritance is used to model “Implemented in terms of”
relationship
May 25, 2013 COMSATS Intitute of Information Technology
Example
class Collection {
...
public:
void AddElement(int);
bool SearchElement(int);
bool SearchElementAgain(int);
bool DeleteElement(int);
};
May 25, 2013 COMSATS Intitute of Information Technology
Example
• If element is not found in the Collection the function SearchElement
will return false
• SearchElementAgain finds the second instance of element in the
collection
May 25, 2013 COMSATS Intitute of Information Technology
Class Set
class Set: private Collection {
private:
...
public:
void AddMember(int);
bool IsMember(int);
bool DeleteMember(int);
};
May 25, 2013 COMSATS Intitute of Information Technology
Class Set
void 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
Specialization (Restriction)
• the 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 Intitute of Information Technology
Specialization (Restriction)
• Specialization (Restriction) can be implemented using private and
protected inheritance
May 25, 2013 COMSATS Intitute of Information Technology
Example – Specialization
(Restriction)
May25,2013
COMSATSIntituteofInformation
Technology
Person
age : [0..125]
Adult
age : [18..125]
setAge( a )
setAge( a )
age = a
If age < 18 then
error
else
age = a
Private Inheritance
Member access in
Base Class Derived Class
Public Private
Protected Private
Private Hidden
class Child: private Parent {…};
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
Example
class 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
“Abstract” Base Class
• In the examples so far, inheritance has been used to add functionality
to an existing class. Now let’s look at an example where inheritance is
used for a different purpose: as part of the original design of a
program.
• Our example models a database of employees of a widget company.
We’ve simplified the situation so that only three kinds of employees
are represented. Managers manage, scientists perform research to
develop better widgets, and laborers operate the dangerous widget-
stamping presses.
• The database stores a name and an employee identification number
for all employees, no matter what their category. However, for
managers, it also stores their titles and golf club dues. For scientists, it
stores the number of scholarly articles they have published. Laborers
need no additional data beyond their names and numbers.
• Our example program starts with a base class employee. This class
handles the employee’s last name and employee number. From this
class three other classes are derived: manager, scientist, and laborer.
The manager and scientist classes contain additional information
about these categories of employee, and member functions to handle
this information, as shown in Figure
May 25, 2013 COMSATS Intitute of Information Technology
May 25, 2013 COMSATS Intitute of Information Technology
Exercise 1
• Imagine a publishing company that markets both book and
audiocassette versions of its works. Create a class publication that
stores the title (a string) and price (type float) of a publication. From
this class derive two classes: book, which adds a page count (type
int), and tape, which adds a playing time in minutes (type float). Each
of these three classes should have a getdata() function to get its data
from the user at the keyboard, and a putdata() function to display its
data. Write a main() program to test the book and tape classes by
creating instances of them, asking the user to fill in data with
getdata(), and then displaying the data with putdata().
May 25, 2013 COMSATS Intitute of Information Technology
Exercise 2
• Start with the publication, book, and tape classes of Exercise 1. Add a
base class sales that holds an array of three floats so that it can record
the 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 book
and tape classes so they are derived from both publication and sales.
An object of class book or tape should input and output sales data
along with its other data. Write a main() function to create a book
object and a tape object and exercise their input/output capabilities.
May 25, 2013 COMSATS Intitute of Information Technology
Exercise 3
• Assume that the publisher in Exercises 1 and 3 decides to add a third
way to distribute books: on computer disk, for those who like to do
their reading on their laptop. Add a disk class that, like book and tape,
is derived from publication. The disk class should incorporate the
same member functions as the other classes. The data item unique to
this class is the disk type: either CD or DVD. You can use an enum type
to store this item. The user could select the appropriate type by
typing c or d.
May 25, 2013 COMSATS Intitute of Information Technology
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 ,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
Thanks
May 25, 2013 COMSATS Intitute of Information Technology
CSC241:
Object Oriented
Programming
Spring 2013
1. Overriding & Overloading
2. Multiple Inheritance
3. Virtual Inheritance
4. Virtual Functions/Members
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
Overriding Member Functions of Base
Class
• Derived class can override the member functions of
its base class
• To override a function the derived class simply
provides a function with the same signature as that of
its base class
May 25, 2013 COMSATS Institute of Information Technology 553
Overriding
May 25, 2013 COMSATS Institute of Information Technology 554
Parent
...
Func1
Child
...
Func1
Overriding
class Parent {
public:
voidFunc1();
voidFunc1(int);
};
class Child: public Parent {
public:
void Func1();
};
May 25, 2013 COMSATS Institute of Information Technology 555
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 duplicate
declaration
May 25, 2013 COMSATS Institute of Information Technology 556
Overriding
class Parent {
public:
void Func1();
void Func1(); //Error
};
May 25, 2013 COMSATS Institute of Information Technology 557
Overriding Member Functions of Base
Class
• Derive class can override member function of base
class such that the working of function is totally
changed
May 25, 2013 COMSATS Institute of Information Technology 558
Example
class Person{
public:
void Walk();
};
class ParalyzedPerson: public Person{
public:
void Walk();
};
May 25, 2013 COMSATS Institute of Information Technology 559
Overriding Member Functions of Base
Class
• Derive class can override member function of base
class such that the working of function is similar to
former implementation
May 25, 2013 COMSATS Institute of Information Technology 560
Example
class 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
Example
class 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
Example
int main(){
Student a(“Ahmad”, “Computer
Science”);
a.Print();
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 563
Output
Output:
Name: Ahmed
Major: Computer Science
May 25, 2013 COMSATS Institute of Information Technology 564
Overriding Member Functions of Base
Class
• Derive class can override member function of base
class such that the working of function is based on
former implementation
May 25, 2013 COMSATS Institute of Information Technology 565
Example
class Student : public Person{
char * major;
public:
Student(char * aName, char* m);
void Print(){
Print();//Print of Person
cout<<“Major:” << major <<endl;
}
...
};
May 25, 2013 COMSATS Institute of Information Technology 566
Example
int main(){
Student a(“Ahmad”, “Computer
Science”);
a.Print();
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 567
Output
• There will be no output as the compiler will call the
print of the child class from print of child class
recursively
• There is no ending condition
May 25, 2013 COMSATS Institute of Information Technology 568
Example
class 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
Example
int main(){
Student a(“Ahmad”, “Computer
Science”);
a.Print();
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 570
Output
Output:
Name: Ahmed
Major: Computer Science
May 25, 2013 COMSATS Institute of Information Technology 571
{Before New Topic……}
• I need Your anonymous Feed Back
• About the Instructor
•&
• About the Course
May 25, 2013 COMSATS Institute of Information Technology 572
Multiple Inheritance
• A class can inherit from more then one class
May 25, 2013 COMSATS Institute of Information Technology 573
Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 574
Transmitter
...
Transmit()
Receiver
...
Receive()
Phone
Example
class Phone: public Transmitter, public
Receiver
{
...
};
May 25, 2013 COMSATS Institute of Information Technology 575
Multiple Inheritance
• Derived class can inherit from public base class as well as private and
protected base classes
class Mermaid:
private Woman, private Fish
May 25, 2013 COMSATS Institute of Information Technology 576
Multiple Inheritance
• The derived class inherits data members and functions form all the
base classes
• Object of derived class can perform all the tasks that an object of
base class can perform
May 25, 2013 COMSATS Institute of Information Technology 577
Example
int main(){
Phone obj;
obj.Transmit();
obj.Receive();
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 578
Multiple Inheritance
• When using public multiple inheritance, the object of derived class
can replace the objects of all the base classes
May 25, 2013 COMSATS Institute of Information Technology 579
Example
int main(){
Phone obj;
Transmitter * tPtr = &obj;
Receiver * rPtr = &obj;
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 580
Multiple Inheritance
• The pointer of one base class cannot be used to call the function of
another base class
• The functions are called based on static type
May 25, 2013 COMSATS Institute of Information Technology 581
Example
int main(){
Phone obj;
Transmitter * tPtr = &obj;
tPtr->Transmit();
tPtr->Receive(); //Error
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 582
Example
int main(){
Phone obj;
Receiver * rPtr = &obj;
rPtr->Receive();
rPtr->Transmit(); //Error
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 583
Multiple Inheritance
• If more than one base class have a function with same signature then
the child will have two copies of that function
• Calling such function will result in ambiguity
May 25, 2013 COMSATS Institute of Information Technology 584
Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 585
Amphibious
Vehicle
Land Vehicle Water Vehicle
Car Boat
Example
class LandVehicle{
public:
int GetMaxLoad();
};
class WaterVehicle{
public:
int GetMaxLoad();
};
May 25, 2013 COMSATS Institute of Information Technology 586
Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
};
int main(){
AmphibiousVehicle obj;
obj.GetMaxLoad(); // Error
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 587
Multiple Inheritance
• Programmer must explicitly specify the class name when calling
ambiguous function
May 25, 2013 COMSATS Institute of Information Technology 588
Example
int main(){
AmphibiousVehicle obj;
obj.LandVehicle::GetMaxLoad();
obj.WaterVehicle::GetMaxLoad();
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 589
Multiple Inheritance
• The ambiguous call problem can arise when dealing with multiple
level of multiple inheritance
May 25, 2013 COMSATS Institute of Information Technology 590
Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 591
Amphibious
Vehicle
Land Vehicle Water Vehicle
Vehicle
Car Boat
Example
class Vehicle{
public:
int GetMaxLoad();
};
class LandVehicle : public Vehicle{
};
class WaterVehicle : public Vehicle{
};
May 25, 2013 COMSATS Institute of Information Technology 592
Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
};
int main(){
AmphibiousVehicle obj;
obj.GetMaxLoad(); // Error
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 593
Example
int main()
{
AmphibiousVehicle obj;
obj.Vehicle::GetMaxLoad(); //Error
return 0;
}
•Vehicle is accessible through two paths
May 25, 2013 COMSATS Institute of Information Technology 594
Multiple Inheritance
May 25, 2013 COMSATS Institute of Information Technology 595
Amphibious
Vehicle
Land Vehicle Water Vehicle
Vehicle
Car Boat
Vehicle
Example
int main(){
AmphibiousVehicle obj;
obj.LandVehicle::GetMaxLoad();
obj.WaterVehicle::GetMaxLoad();
return 0;
}
May 25, 2013 COMSATS Institute of Information Technology 596
Multiple Inheritance
• Data member must be used with care when dealing with more then
one level on inheritance
May 25, 2013 COMSATS Institute of Information Technology 597
Example
class Vehicle{
protected:
int weight;
};
class LandVehicle : public Vehicle{
};
class WaterVehicle : public Vehicle{
};
May 25, 2013 COMSATS Institute of Information Technology 598
Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
public:
AmphibiousVehicle(){
LandVehicle::weight = 10;
WaterVehicle::weight = 10;
}
};
• There are multiple copies of data member weight
May 25, 2013 COMSATS Institute of Information Technology 599
Memory View
May25,2013
COMSATSInstituteofInformation
Technology
600
Data Members of
Vehicle
Data Members of
LandVehicle
Data Members of AmphibiousVehicle
Data Members of
Vehicle
Data Members of
WaterVehicle
Virtual Inheritance
• In virtual inheritance there is exactly one copy of the anonymous base
class object
May 25, 2013 COMSATS Institute of Information Technology 601
Example
class Vehicle{
protected:
int weight;
};
class LandVehicle :
public virtual Vehicle{
};
class WaterVehicle :
public virtual Vehicle{
};
May 25, 2013 COMSATS Institute of Information Technology 602
Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
public:
AmphibiousVehicle(){
weight = 10;
}
};
May 25, 2013 COMSATS Institute of Information Technology 603
Memory View
May 25, 2013 COMSATS Institute of Information Technology 604
Data Members of Vehicle
Data Members of
LandVehicle
Data Members of AmphibiousVehicle
Data Members of
WaterVehicle
Virtual Inheritance
• Virtual inheritance must be used when necessary
• There are situation when programmer would want to use two distinct
data members inherited from base class rather then one
May 25, 2013 COMSATS Institute of Information Technology 605
Example
May 25, 2013 COMSATS Institute of Information Technology 606
Student
BS Student MS Student PhD Student
MS/PhD Student
GPA
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 ,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
Thanks
May 25, 2013 COMSATS Institute of Information Technology 608
CSC241:
Object Oriented
Programming
Spring 2013
1. Generic Programming
2. Templates
Please turn OFF your Mobile Phones!
Saturday, May 25, 2013
Farhan Aadil
Quiz
• Explain “Diamond of Death” with help of Class Diagram, also write
code for your class diagram.
May 25, 2013 COMSATS Institute of Information Technology 610
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
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
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 ] << “, ”;
}
...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 ] << “, ”;
}
...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 ] << “, ”;
}
...Motivation
• Now if we want to change the way function prints the array. e.g. from
1, 2, 3, 4, 5
to
1 - 2 - 3 - 4 - 5
...Motivation
• Now consider the Array class that wraps an array of integers
class Array {
int* pArray;
int size;
public:
…
};
...Motivation
• What if we want to use an Array class that wraps arrays of double?
class Array {
double* pArray;
int size;
public:
…
};
...Motivation
• What if we want to use an Array class that wraps arrays of boolean
variables?
class Array {
bool* pArray;
int size;
public:
…
};
...Motivation
• Now if we want to add a function sum to Array class, we have to
change all the three classes
Generic Programming
• Generic programming refers to programs containing generic
abstractions
• A generic program abstraction (function, class) can be parameterized
with a type
• Such abstractions can work with many different types of data
Advantages
• Reusability
• Writability
• Maintainability
Templates
• In C++ generic programming is done using templates
• Two kinds
• Function Templates
• Class Templates
• Compiler generates different type-specific copies from a single
template
Function Templates
• A function template can be parameterized to operate on different
types of data
Declaration
template< class T >
void funName( T x );
// OR
template< typename T >
void funName( T x );
// OR
template< class T, class U, … >
void funName( T x, U y, … );
Example – Function Templates
• Following function template prints an array having almost any type of
elements:
template< typename T >
void printArray( T* array, int size )
{
for ( int i = 0; i < size; i++ )
cout << array[ i ] << “, ”;
}
…Example – Function Templates
int 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;
}
Explicit Type Parameterization
• A function template may not have any parameter
template <typename T>
T getInput() {
T x;
cin >> x;
return x;
}
…Explicit Type Parameterization
int main() {
int x;
x = getInput(); // Error!
double y;
y = getInput(); // Error!
}
…Explicit Type Parameterization
int main() {
int x;
x = getInput< int >();
double y;
y = getInput< double >();
}
User-defined Specializations
• A template may not handle all the types successfully
• Explicit specializations need to be provided for specific type(s)
Example – User Specializations
template< typename T >
bool isEqual( T x, T y ) {
return ( x == y );
}
… Example – User Specializations
int main {
isEqual( 5, 6 );// OK
isEqual( 7.5, 7.5 ); // OK
isEqual( “abc”, “xyz” );
// Logical Error!
return 0;
}
… Example – User Specializations
template< >
bool isEqual< const char* >(
const char* x, const char* y ) {
return ( strcmp( x, y ) == 0 );
}
… Example – User Specializations
int main {
isEqual( 5, 6 );
// Target: general template
isEqual( 7.5, 7.5 );
// Target: general template
isEqual( “abc”, “xyz” );
// Target: user specialization
return 0;
}
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 ,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
Thanks
May 25, 2013 COMSATS Institute of Information Technology 638
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;
• }
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): ";

All in 1

  • 1.
  • 2.
    CSC241: Object Oriented Programming Spring 2013 1.Starting OOP May25,2013COMSATSInstituteofInformationTechnology 2 Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 3.
    Study Assignment • Ihope 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
  • 5.
    Object-Orientation (OO) May 25, 2013COMSATS Institute of Information Technology 5
  • 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 aModel? • 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 – OOModel May 25, 2013 COMSATS Institute of Information Technology 9
  • 10.
    …Example – OOModel • 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 anObject? 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 isan Object? An object has • State (attributes) • Well-defined behaviour (operations) • Unique identity May 25, 2013 COMSATS Institute of Information Technology 13
  • 14.
    Example – Aliis 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 – Caris 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 – Timeis 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 – Dateis 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 Isan 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 sharetwo 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 aremodeled 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-worldobjects 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 newthinking … • 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 newthinking … • 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 newthinking … • 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 newthinking … • 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 isa 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 May25, 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 anOO 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 ofClasses May 25, 2013 COMSATS Institute of Information Technology 41 (Class Name) (attributes) (operations) (Class Name) Normal Form Suppressed Form
  • 42.
    Example – GraphicalRepresentation of Classes May 25, 2013 COMSATS Institute of Information Technology 42 Circle center radius draw computeArea Normal Form Suppressed Form Circle
  • 43.
    Example – GraphicalRepresentation 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 childinherits 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 May25, 2013 COMSATS Institute of Information Technology 46 Person Teacher DoctorStudent
  • 47.
    Example – Inheritance May25, 2013 COMSATS Institute of Information Technology 47 Shape Circle TriangleLine
  • 48.
    Inheritance – “ISA” 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 – “ISA” 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 – “ISA” 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 OrientedProgramming 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
  • 57.
    Thanks May 25, 2013COMSATS Institute of Information Technology 57
  • 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 withInheritance • Generalization • Subtyping (extension) • Specialization (restriction) May 25, 2013 COMSATS Institute of Information Technology 60
  • 61.
    Generalization • In OOmodels, 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 May25, 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 May25, 2013 COMSATS Institute of Information Technology 63 Shape color vertices move setColor Circle radius computeArea Line length getLength Triangle angle computeArea
  • 64.
    Example – Generalization May25, 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 May25, 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-typingmeans 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) • Specializationmeans 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) May25, 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) May25, 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 classmay 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 – SpecificBehaviour 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 May25, 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 May25, 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 – ImprovePerformance • 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 • Anabstract 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 – AbstractClasses • Here, Person is an abstract classMay 25, 2013 COMSATS Institute of Information Technology 79 Teacher DoctorStudent Person name age gender eat walk
  • 80.
    Example – AbstractClasses • Here, Vehicle is an abstract classMay 25, 2013 COMSATS Institute of Information Technology 80 Bus TruckCar Vehicle color model accelerate applyBrakes
  • 81.
    Concrete Classes • Aconcrete 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 – ConcreteClasses • 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 – ConcreteClasses 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 • Wemay want to reuse characteristics of more than one parent class May 25, 2013 COMSATS Institute of Information Technology 84
  • 85.
    Example – MultipleInheritance May 25, 2013 COMSATS Institute of Information Technology 85 Mermaid
  • 86.
    Example – MultipleInheritance May 25, 2013 COMSATS Institute of Information Technology 86 Mermaid Woman Fish
  • 87.
    Example – MultipleInheritance May 25, 2013 COMSATS Institute of Information Technology 87 Amphibious Vehicle
  • 88.
    Example – MultipleInheritance May 25, 2013 COMSATS Institute of Information Technology 88 Amphibious Vehicle Land Vehicle Water Vehicle Vehicle Car Boat
  • 89.
    Problems with MultipleInheritance • Increased complexity • Reduced understanding • Duplicate features May 25, 2013 COMSATS Institute of Information Technology 89
  • 90.
    Problem – DuplicateFeatures • Which eat operation Mermaid inherits? May 25, 2013 COMSATS Institute of Information Technology 90 Mermaid Woman Fish eat … eat …
  • 91.
    Solution – Overridethe 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 – DuplicateFeatures (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 DiamondProblem • 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 inan 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 • Isthe 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 SimpleAssociation • 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 • Wecan 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 • Wecan navigate in both directions • Denoted by a line between the associated objects May 25, 2013 COMSATS Institute of Information Technology 101
  • 102.
    Example – Two-wayAssociation • Employee works for company • Company employs employees May 25, 2013 COMSATS Institute of Information Technology 102 Employee Company works-for 1*
  • 103.
    Example – Two-wayAssociation • 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 • Associatesobjects 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 – BinaryAssociation • 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 – BinaryAssociation • Association “drives” associates objects of exactly two classes May 25, 2013 COMSATS Institute of Information Technology 106 Ali Car drives *1
  • 107.
    Ternary Association • Associatesobjects 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 – TernaryAssociation • Objects of exactly three classes are associated May 25, 2013 COMSATS Institute of Information Technology 108 Student Teacher Course 1 * *
  • 109.
    Example – TernaryAssociation • Objects of exactly three classes are associated May 25, 2013 COMSATS Institute of Information Technology 109 Project Language Person * 1 *
  • 110.
    N-ary Association • Anassociation between 3 or more classes • Practical examples are very rare May 25, 2013 COMSATS Institute of Information Technology 110
  • 111.
    Composition • An objectmay 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 – Compositionof Ali May 25, 2013 COMSATS Institute of Information Technology 112 Ali Body Arm Head Leg 1 1 2 2
  • 113.
    Example – Compositionof 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 – Compositionis 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 – Compositionis 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 objectmay 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 May25, 2013 COMSATS Institute of Information Technology 118 Room Cupboard Bed Chair Table * 1 1 1
  • 119.
    Example – Aggregation May25, 2013 COMSATS Institute of Information Technology 119 Garden Plant*
  • 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 – Aggregationis 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 – Aggregationis 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 OrientedProgramming 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
  • 124.
    Thanks May 25, 2013COMSATS Institute of Information Technology 124
  • 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 May25, 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 inan 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 • Isthe 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 SimpleAssociation • 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 • Wecan 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 • Wecan navigate in both directions • Denoted by a line between the associated objects May 25, 2013 COMSATS Intitute of Information Technology 134
  • 135.
    Example – Two-wayAssociation • Employee works for company • Company employs employees May 25, 2013 COMSATS Intitute of Information Technology 135 Employee Company works-for 1*
  • 136.
    Example – Two-wayAssociation • 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 • Associatesobjects 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 – BinaryAssociation • 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 – BinaryAssociation • Association “drives” associates objects of exactly two classes May 25, 2013 COMSATS Intitute of Information Technology 139 Ali Car drives *1
  • 140.
    Ternary Association • Associatesobjects 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 – TernaryAssociation • Objects of exactly three classes are associated May 25, 2013 COMSATS Intitute of Information Technology 141 Student Teacher Course 1 * *
  • 142.
    Example – TernaryAssociation • Objects of exactly three classes are associated May 25, 2013 COMSATS Intitute of Information Technology 142 Project Language Person * 1 *
  • 143.
    N-ary Association • Anassociation 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 objectmay 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 May25, 2013 COMSATS Intitute of Information Technology 146 Composition among classes is shown as solid diamond arrowhead in UML Class Diagram.
  • 147.
    Example – Compositionof Ali May 25, 2013 COMSATS Intitute of Information Technology 147 Ali Body Arm Head Leg 1 1 2 2
  • 148.
    Example – Compositionof 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 – Compositionis 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 – Compositionis 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 isa ‘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 objectmay 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 May25, 2013 COMSATS Intitute of Information Technology 155 Aggregation among classes is shown as open diamond arrowhead in UML Class Diagram.
  • 155.
    Example – Aggregation May25, 2013 COMSATS Intitute of Information Technology 156 Room Cupboard Bed Chair Table * 1 1 1
  • 156.
    Example – Aggregation May25, 2013 COMSATS Intitute of Information Technology 157 Garden Plant*
  • 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 – Aggregationis 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 – Aggregationis 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 May25, 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 • Aclass 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 • Derivedclass 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 – ClassCompatibility 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 – ClassCompatibility 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 OOModel • 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 May25, 2013 COMSATS Intitute of Information Technology 172 Shape Line Circle Triangle draw draw draw draw draw View
  • 172.
    Example – Polymorphism May25, 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
  • 176.
    Object-Oriented Modeling An Example May 25,2013 COMSATS Intitute of Information Technology 177
  • 177.
    Problem Statement • Developa 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 nounsin 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 irrelevantclasses • Editor – Very broad scope • User – Out of system boundary May 25, 2013 COMSATS Intitute of Information Technology 180
  • 180.
    …Identify Classes Add classesby 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 verbsconnecting 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 Verifyaccess 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 Verifyaccess 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 propertiesof the object • From the problem statement • Properties are not mentioned May 25, 2013 COMSATS Intitute of Information Technology 188
  • 188.
    …Identify Attributes Extract propertiesof 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 propertiesof 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 verbsconnected 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 Eliminateirrelevant operations • Develop – out of system boundary • Behave – have broad semantics May 25, 2013 COMSATS Intitute of Information Technology 193
  • 193.
    …Identify Operations Following areselected operations: May 25, 2013 COMSATS Intitute of Information Technology 194 • Line – Draw – Select – Move – Rotate • Circle – Draw – Select – Move – Rotate
  • 194.
    …Identify Operations Following areselected operations: May 25, 2013 COMSATS Intitute of Information Technology 195 • Triangle – Draw – Select – Move – Rotate • Shape – Draw – Select – Move – Rotate
  • 195.
    …Identify Operations Following areselected operations: May 25, 2013 COMSATS Intitute of Information Technology 196 • Group – Draw – Select – Move – Rotate • Menu – Open – Select – Move – Rotate
  • 196.
    …Identify Operations Extract operationsusing domain knowledge May 25, 2013 COMSATS Intitute of Information Technology 197 • View – Add – Remove – Group – Show – Select – Move – Rotate
  • 197.
  • 198.
    Identify Inheritance Search “isa 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 analyzingrequirements • “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 ObjectModel • 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 ObjectModel 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 ObjectModel Share attributes • Shape – Line, Circle, Triangle and Group • Color, vertices May 25, 2013 COMSATS Intitute of Information Technology 203
  • 203.
    …Refining the ObjectModel Share operations • Shape – Line, Circle, Triangle and Group • Select • Move • Rotate May 25, 2013 COMSATS Intitute of Information Technology 204
  • 204.
    …Refining the ObjectModel Share the interface and override implementation • Shape – Line, Circle, Triangle and Group • Draw May 25, 2013 COMSATS Intitute of Information Technology 205
  • 205.
  • 206.
  • 207.
    Class • Class isa 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 isan object • Student is an object • Both has some attributes and some behaviors May 25, 2013 COMSATS Intitute of Information Technology 209
  • 209.
    Uses • The problembecomes 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 includedetails 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 NewUser 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
  • 215.
    Example Student aStudent; aStudent.rollNo =514; aStudent.rollNo = -514; //Error May 25, 2013 COMSATS Intitute of Information Technology 216
  • 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 • Membersof 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; voidsetRollNo(int aNo); }; Student aStudent; aStudent.rollNo; May 25, 2013 COMSATS Intitute of Information Technology 220 Error
  • 220.
    struct -> classtransition! 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.
  • 223.
    Access specifiers May 25,2013 COMSATS Intitute of Information Technology 224
  • 224.
    Access specifiers • Thereare 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
  • 226.
    Example class Student{ ... int rollNo; public: voidsetRollNo(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 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) • InstallIBM 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 OrientedProgramming 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
  • 234.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 235
  • 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
  • 236.
    Review • Class • Concept •Definition • Data members • Member Functions • Access specifier
  • 237.
    Member Functions • Memberfunctions 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 ClassBody class ClassName { … public: ReturnType FunctionName() { … } };
  • 240.
    Example •Define a classof student that has a roll number. This class should have a function that can be used to set the roll number
  • 241.
    Example class Student{ int rollNo; public: voidsetRollNo(int aRollNo){ rollNo = aRollNo; } };
  • 242.
    Function Outside ClassBody class ClassName{ … public: ReturnType FunctionName(); }; ReturnType ClassName::FunctionName() { … } Scope resolution operator
  • 243.
    Example class Student{ … int rollNo; public: voidsetRollNo(int aRollNo); }; void Student::setRollNo(int aRollNo){ … rollNo = aRollNo; }
  • 244.
    Inline Functions • Insteadof 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
  • 245.
    Example inline int Area(intlen, int hi) { return len * hi; } int main() { cout << Area(10,20); }
  • 246.
    Inline Functions • Ifwe 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
  • 247.
    Example class Student{ int rollNo; public: voidsetRollNo(int aRollNo){ … rollNo = aRollNo; } };
  • 248.
    Example class Student{ … public: inline voidsetRollNo(int aRollNo); }; void Student::setRollNo(int aRollNo){ … rollNo = aRollNo; }
  • 249.
    Example class Student{ … public: void setRollNo(intaRollNo); }; inline void Student::setRollNo(int aRollNo){ … rollNo = aRollNo; }
  • 250.
    Example class Student{ … public: inline voidsetRollNo(int aRollNo); }; inline void Student::setRollNo(int aRollNo){ … rollNo = aRollNo; }
  • 251.
  • 252.
    Constructor • Constructor isused 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.) • Constructoris a special function having same name as the class name • Constructor does not have return type • Constructors are commonly public members
  • 254.
  • 255.
    Example int main() { Student aStudent; /*constructoris implicitly called at this point*/ }
  • 256.
    Default Constructor • Constructorwithout 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
  • 257.
    Example class Student { int rollNo; char*name; float GPA; public: … //no constructors };
  • 258.
    Example Compiler generated defaultconstructor { rollNo = 0; GPA = 0.0; name = NULL; }
  • 259.
    Constructor Overloading • Constructorscan have parameters • These parameters are used to initialize the data members with user supplied data
  • 260.
    Example class Student{ … public: Student(); Student(char *aName); Student(char * aName, int aRollNo); Student(int aRollNo, int aRollNo, float aGPA); };
  • 261.
    Example Student::Student(int aRollNo, char *aName){ if(aRollNo < 0){ rollNo = 0; } else { rollNo = aRollNo; } … }
  • 262.
    Example int main() { Student student1; Studentstudent2(“Name”); Student student3(”Name”, 1); Student student4(”Name”,1,4.0); }
  • 263.
    Constructor Overloading • Usedefault parameter value to reduce the writing effort
  • 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 OrientedProgramming 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 correctlySearch 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
  • 267.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 268
  • 268.
    CSC241: Object Oriented Programming Spring 2013 1.Functions Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 269.
    Revision • Chapter 5of book May 25, 2013 COMSATS Intitute of Information Technology 270
  • 270.
    Functions May 25, 2013COMSATS 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.
  • 271.
    Return type Input argumentsMay25, 2013 COMSATS Intitute of Information Technology 272
  • 272.
    Functions May 25, 2013COMSATS 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, 2013COMSATS 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, 2013COMSATS 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, 2013COMSATS 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; }
  • 279.
    Recursion May 25, 2013COMSATS Intitute of Information Technology 280
  • 280.
    References • “Object OrientedProgramming 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
  • 281.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 282
  • 282.
    CSC241: Object Oriented Programming Spring 2013 1.Constructors May 25, 2013 COMSATS Intitute of Information Technology 283 Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 283.
  • 284.
    Constructor • Constructor isused 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.) • Constructoris a special function having same name as the class name • Constructor does not have return type • Constructors are commonly public members
  • 286.
  • 287.
    Example int main() { Student aStudent; /*constructoris implicitly called at this point*/ }
  • 288.
    Default Constructor • Constructorwithout 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
  • 289.
    Example class Student { int rollNo; char*name; float GPA; public: … //no constructors };
  • 290.
    Example Compiler generated defaultconstructor { rollNo = 0; GPA = 0.0; name = NULL; }
  • 291.
    Constructor Overloading • Constructorscan have parameters • These parameters are used to initialize the data members with user supplied data
  • 292.
    Example class Student{ … public: Student(); Student(char *aName); Student(char * aName, int aRollNo); Student(char * aName, int aRollNo, float aGPA); };
  • 293.
    Example Student::Student(int aRollNo, char *aName){ if(aRollNo < 0){ rollNo = 0; } else { rollNo = aRollNo; } … }
  • 294.
    Example int main() { Student student1; Studentstudent2(“Name”); Student student3(”Name”, 1); Student student4(”Name”,1,4.0); }
  • 295.
    Constructor Overloading • Usedefault parameter value to reduce the writing effort
  • 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 • Copyconstructor are used when: • Initializing an object at the time of creation • When an object is passed by value to a function
  • 298.
    Example void func1(Student student){ … } intmain(){ Student studentA; Student studentB = studentA; func1(studentA); }
  • 299.
    Copy Constructor (Syntax) Student::Student( constStudent &obj){ rollNo = obj.rollNo; name = obj.name; GPA = obj.GPA; }
  • 300.
    Shallow Copy • Whenwe initialize one object with another then the compiler copies state of one object to the other • This kind of copying is called shallow copying
  • 301.
    Example Student studentA; Student studentB= studentA; Name GPA RollNo studentA Name GPA RollNo studentB A H M A D … Memory
  • 302.
    Assignment • Lab AssignmentNo 3 May 25, 2013 COMSATS Intitute of Information Technology 303
  • 303.
    References • “Object OrientedProgramming 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
  • 304.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 305
  • 305.
    CSC241: Object Oriented Programming Spring 2013 1.Destructor Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 306.
  • 307.
    Destructor • You mightguess 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 aresituations where designer wants to return reference to current object from a function •In such cases reference is taken from this pointer like (*this)
  • 310.
    Example Student Student::setRollNo(int aNo) { … return*this; } Student Student::setName(char *aName) { … return *this; }
  • 311.
    Example int main() { Student aStudent; StudentbStudent; bStudent = aStudent.setName(“Ahmad”); … bStudent = aStudent.setName(“Ali”).setRollNo(2); return 0; }
  • 312.
    Separation of interfaceand 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 aretwo 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() voidsetNumber (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
  • 315.
    Example class Complex{ //old floatx; float y; public: void setNumber(float i, float j){ x = i; y = j; } … };
  • 316.
    Example class Complex{ //new floatz; float theta; public: void setNumber(float i, float j){ theta = arctan(j/i); … } … };
  • 317.
    Advantages •User is onlyconcerned about ways of accessing data (interface) •User has no concern about the internal representation and implementation of the class
  • 318.
    Separation of interfaceand 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
  • 319.
    Student.h class Student{ int rollNo; public: voidsetRollNo(int aRollNo); int getRollNo(); … };
  • 320.
    Student.cpp #include “student.h” void Student::setRollNo(intaNo){ … } int Student::getRollNo(){ … }
  • 321.
  • 322.
    Classes, Objects andMemory • 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, 2013COMSATS Intitute of Information Technology 324
  • 324.
    References • “Object OrientedProgramming 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
  • 325.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 326
  • 326.
    CSC241: Object Oriented Programming Spring 2013 1.Static class member 2. Const member function Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan 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 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 memberdata 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 inmemory • 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 packingin 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 •Thereare 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
  • 335.
    Example bool Student::isRollNo(int aNo){ if(rollNo= = aNo){ return true; } return false; } May 25, 2013 COMSATS Intitute of Information Technology 336
  • 336.
    Example bool Student::isRollNo(int aNo){ /*undetectedtyping mistake*/ if(rollNo = aNo){ return true; } return false; } May 25, 2013 COMSATS Intitute of Information Technology 337
  • 337.
    Example bool Student::isRollNo (int aNo)const{ /*compilererror*/ if(rollNo = aNo){ return true; } return false; } May 25, 2013 COMSATS Intitute of Information Technology 338
  • 338.
    const Member Functions •Keywordconst is placed at the end of the parameter list May 25, 2013 COMSATS Intitute of Information Technology 339
  • 339.
    const Member Functions Declaration: classClassName{ ReturnVal Function() const; }; Definition: ReturnVal ClassName::Function() const{ … } May 25, 2013 COMSATS Intitute of Information Technology 340
  • 340.
    Example class Student{ public: int getRollNo()const { return rollNo; } }; May 25, 2013 COMSATS Intitute of Information Technology 341
  • 341.
    const Functions •Constant memberfunctions 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 andDestructors 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
  • 343.
    Example class Time{ public: Time() const{} //error… ~Time() const {} //error… }; May 25, 2013 COMSATS Intitute of Information Technology 344
  • 344.
    const Function •Constant memberfunction 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, 2013COMSATS Intitute of Information Technology 347
  • 347.
    References • “Object OrientedProgramming 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
  • 348.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 349
  • 349.
    CSC241: Object Oriented Programming Spring 2013 1.Arrays & String (Chapter 7) Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 350.
    Arrays  In everydaylife 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 andWriting 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> usingnamespace 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 Accesson 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 ReverseOrder #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 toFunction #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; }
  • 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 Arrays 0x22ff40= 11 0x22ff44 = 12 0x22ff48 = 13 0x22ff4C = 21 0x22ff50 = 22 0x22ff54 = 23 ary[0][0]= ary[0][1]= ary[0][2]= ary[1][0]= ary[1][1]= ary[1][2]=       232221 131211
  • 359.
    2-Dimensional Arrays #include <iostream> usingnamespace 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 Arrays 0x22ff30 =11 0x22ff34 = 12 0x22ff38 = 13 0x22ff3C = 21 0x22ff40 = 22 0x22ff44 = 23 ary[0][0]= ary[0][1]= ary[0][2]= ary[1][0]= ary[1][1]= ary[1][2]= 0x22ff48 = 31 0x22ff4C = 32 0x22ff50 = 33 ary[2][0]= ary[2][1]= ary[2][2]=           333231 232221 131211
  • 361.
    Calculating Square ofa 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 Arrayto 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 Arrayto 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 Arrayto 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 UsingBubble 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 UsingBubble 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] <<" "; }
  • 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 string char str[MAX]; // string variable str cout << "nEnter a string: "; // cin.get() means a member function get() of the stream // class of which cin is an object cin.get(str, MAX); // put string in str // first argument to get() is the array address where the // string being input will be placed. // The second argument specifies the maximum size of the // array cout << "You entered: " << str << endl; return 0; }
  • 369.
    Copying a Stringthe Hard Way // strcopy1.cpp // copies a string using a for loop #include <iostream> #include <cstring> //for strlen() using namespace std; int main(){ //initialized string char str1[] = "Oh, Captain, my Captain! " "our fearful trip is done"; const int MAX = 80; int j; // MAX is size of str2 buffer char str2[MAX]; //empty string for( j=0; j<strlen(str1); j++) //copy strlen characters str2[j] = str1[j]; // from str1 to str2 str2[j] = '0'; //insert NULL at end cout << str2 << endl; //display str2 system("PAUSE"); return 0; }
  • 370.
    Copying a Stringthe 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 buffer char str2[MAX]; //empty string strcpy(str2, str1); //copy str1 to str2 cout << str2 << endl; //display str2 system("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 array const int MAX = 10; //maximum size of each string //An array of strings char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" , "Saturday" }; for( int j=0 ; j<DAYS ; j++) //display every string cout << star[j] << endl; system("PAUSE"); return 0; }
  • 372.
  • 373.
    Lab Task Write aand test a program to calculate Determinant and Reverse of a 3x3 matrix
  • 374.
    References • “Object OrientedProgramming 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 376
  • 375.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 377
  • 376.
    CSC241: Object Oriented Programming Spring 2013 1.Composition 2. Aggregation 3. Friend Functions Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan 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.
  • 379.
    Example (Aggregation) int main(){ Studentobj; Student *ptr; ptr = &obj; ptr->setRollNo(10); return 0; }
  • 380.
    Allocation with newOperator • new operator can be used to create objects at runtime
  • 381.
    Example int main(){ Student *ptr; ptr= new Student; ptr->setRollNo(10); return 0; }
  • 382.
    Example int main(){ Student *ptr; ptr= new Student(“Ali”); ptr->setRollNo(10); return 0; }
  • 383.
    Breakup of newOperation • new operator is decomposed as follows • Allocating space in memory • Calling the appropriate constructor
  • 384.
    Case Study Design aclass date through which user must be able to perform following operations • Get and set current day, month and year • Increment by x number of days, months and year • Set default date
  • 385.
    Attributes • Attributes thatcan be seen in this problem statement are • Day • Month • Year • Default date
  • 386.
    Attributes • The defaultdate is a feature shared by all objects • This attribute must be declared a static member
  • 387.
    Attributes in Date.h classDate { int day; int month; int year; static Date defaultDate; … };
  • 388.
    Interfaces • getDay • getMonth •getYear • setDay • setMonth • setYear • addDay • addMonth • addYear • setDefaultDate
  • 389.
    Interfaces • As thedefault date is a static member the interface setDefaultDate should also be declared static
  • 390.
    Interfaces in Date.h classDate{ … public: void setDay(int aDay); int getDay() const; void addDay(int x); … … };
  • 391.
    Interfaces in Date.h classDate{ … public: static void setDefaultDate( int aDay,int aMonth, int aYear); … };
  • 392.
    Constructors and Destructorsin Date.h Date(int aDay = 0, int aMonth= 0, int aYear= 0); ~Date(); //Destructor };
  • 393.
    Implementation of DateClass • The static member variables must be initialized Date Date::defaultDate (07,3,2013);
  • 394.
    Constructors Date::Date(int aDay, intaMonth, int aYear) { if(aDay==0) { this->day = defaultDate.day; } else{ setDay(aDay); } //similarly for other members }
  • 395.
    Destructor • We arenot required to do any house keeping chores in destructor Date::~Date { }
  • 396.
    Getter and Setter voidDate::setMonth(int a){ if(a > 0 && a <= 12){ month = a; } int getMonth() const{ return month; }
  • 397.
    addYear void Date::addYear(int x){ year+= x; if(day == 29 && month == 2 && !leapyear(year)){ day = 1; month = 3; } }
  • 398.
    Helper Function class Date{ … private: boolleapYear(int x) const; … };
  • 399.
    Helper Function bool Date::leapYear(intx) const{ if((x%4 == 0 && x%100 != 0) || (x%400==0)){ return true; } return false; }
  • 400.
    setDefaultDate void Date::setDefaultDate( int d,int m, int y){ if(d >= 0 && d <= 31){ day = d; } … }
  • 401.
    Aggregation Composition vs. Aggregation ►Aggregationis a weak relationship Room(char *, int) ~Room() FoldChair(int) : bool … Chair() DoSomething() : void FoldChair() : bool UnFoldChair() : bool ~Chair() … area : float chairs[50]:Chair * Room … Chair
  • 402.
    Aggregation ►In aggregation, apointer or reference to an object is created inside a class ►The sub-object has a life that is NOTdependant on 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 may not be destroyed
  • 403.
    Aggregation class Room{ private: float area; Chair* chairs[50]; Public: Room(); void AddChair(Chair *, int chairNo); Chair * GetChair(int chairNo); bool FoldChair(int chairNo); … };
  • 404.
    Aggregation Room::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.
    Aggregation Chair * Room::GetChair(intchairNo){ if(chairNo >= 0 && chairNo < 50) return chairs[chairNo]; else return NULL; } bool Room::FoldChair(int chairNo){ if(chairNo >= 0 && chairNo < 50) return chairs[chairNo]->FoldChair(); else return false; }
  • 406.
    Aggregationint main(){ Chair ch1; { Roomr1; r1.AddChair(&ch1, 1); r1.FoldChair(1); } ch1.UnFoldChair(1); return 0; }
  • 407.
    Friend Functions►Consider thefollowing class: class X{ private: int a, b; public: void MemberFunction(); … }
  • 408.
    Friend Functions►Global function: voidDoSomething(X obj){ obj.a = 3; //Error obj.b = 4; //Error }
  • 409.
    Friend Functions►In orderto access the member variables of the class, function definition 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 members of class X
  • 410.
    Friend Functions ►Prototypes offriend functions appear in the class definition ►But friend functions are NOT member functions
  • 411.
    Friend Functions ►Friend functionscan be placed anywhere in the class without any effect ►Access specifiers don’t affect friend functions or classes class X{ ... private: friend void DoSomething(X); public: friend void DoAnything(X); ... };
  • 412.
    Friend Functions ►While thedefinition of the friend function is: void DoSomething(X obj){ obj.a = 3; // No Error obj.b = 4; // No Error … } ►friend keyword is not given in definition
  • 413.
    Friend Functions ►If keywordfriend is used in the function definition, it’s a syntax error //Error… friend void DoSomething(X obj){ … }
  • 414.
    Friend Classes •Similarly, oneclass can also be made friend of another class: class X{ friend class Y; … }; •Member functions of class Y can access private data members of class X
  • 415.
    Friend Classes •Example: class X{ friendclass Y; private: int x_var1, x_var2; ... };
  • 416.
    Friend Classes class Y{ private: inty_var1, y_var2; X objX; public: void setX(){ objX.x_var1 = 1; } };
  • 417.
    Friend Classes int main(){ YobjY; objY.setX(); return 0; }
  • 418.
    References • “Object OrientedProgramming 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 420
  • 419.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 421
  • 420.
    CSC241: Object Oriented Programming Spring 2013 1.Operator Overloading May25,2013 COMSATSIntituteofInformation Technology 422 Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 421.
    Operator overloading ►Consider thefollowing class: class Complex{ private: double real, img; public: Complex Add(const Complex &); Complex Subtract(const Complex &); Complex Multiply(const Complex &); … } May25,2013 COMSATSIntituteofInformation Technology 423
  • 422.
    Operator overloading ►Function implementation: ComplexComplex::Add( const Complex & c1){ Complex t; t.real = real + c1.real; t.img = img + c1.img; return t; } May25,2013 COMSATSIntituteofInformation Technology 424
  • 423.
    Operator overloading ►The followingstatement: Complex c3 = c1.Add(c2); Adds the contents of c2 to c1 and assigns it to c3 (copy constructor) May25,2013 COMSATSIntituteofInformation Technology 425
  • 424.
    Operator overloading ►To performoperations in a single mathematical statement e.g: c1+c2+c3+c4 ►We have to explicitly write: ►c1.Add(c2.Add(c3.Add(c4))) May25,2013 COMSATSIntituteofInformation Technology 426
  • 425.
    Operator overloading ►Alternative wayis: ► t1 = c3.Add(c4); ► t2 = c2.Add(t1); ► t3 = c1.Add(t2); May25,2013 COMSATSIntituteofInformation Technology 427
  • 426.
    Operator overloading ►If themathematical expression is big: • Converting it to C++ code will involve complicated mixture of function calls • Less readable • Chances of human mistakes are very high • Code produced is very hard to maintain May25,2013 COMSATSIntituteofInformation Technology 428
  • 427.
    Operator overloading ►C++ providesa very elegant solution: ►“Operator overloading” ►C++ allows you to overload common operators like +, - or * etc… ►Mathematical statements don’t have to be explicitly converted into function calls May25,2013 COMSATSIntituteofInformation Technology 429
  • 428.
    Operator overloading ►Assume thatoperator + has been overloaded ►Actual C++ code becomes: c1+c2+c3+c4 ►The resultant code is very easy to read, write and maintain May25,2013 COMSATSIntituteofInformation Technology 430
  • 429.
    Operator overloading ►C++ automaticallyoverloads operators for pre-defined types ►Example of predefined types: int float double char long May25,2013 COMSATSIntituteofInformation Technology 431
  • 430.
    Operator overloading ►Example: float x; inty; x = 102.02 + 0.09; Y = 50 + 47; May25,2013 COMSATSIntituteofInformation Technology 432
  • 431.
    Operator overloading ►The compilerprobably calls the correct overloaded low level function for addition i.e: // for integer addition: Add(int a, int b) // for float addition: Add(float a, float b) May25,2013 COMSATSIntituteofInformation Technology 433
  • 432.
    Operator overloading ►Operator functionsare not usually called directly ►They are automatically invoked to evaluate the operations they implement May25,2013 COMSATSIntituteofInformation Technology 434
  • 433.
    Operator overloading ►List ofoperators that can be overloaded in C++: May25,2013 COMSATSIntituteofInformation Technology 435
  • 434.
    Operator overloading ►List ofoperators that can’t be overloaded: ►Reason: They take name, rather than value in their argument except for ?: ►?: is the only ternary operator in C++ and can’t be overloaded May25,2013 COMSATSIntituteofInformation Technology 436
  • 435.
    Operator overloading ►The precedenceof an operator is NOT affected due to overloading ►Example: c1*c2+c3 c3+c2*c1 both yield the same answer May25,2013 COMSATSIntituteofInformation Technology 437
  • 436.
    Operator overloading ►Associativity isNOT changed due to overloading ►Following arithmetic expression always is evaluated from left to right: c1 + c2 + c3 + c4 May25,2013 COMSATSIntituteofInformation Technology 438
  • 437.
    Operator overloading ►Unary operatorsand assignment operator are right associative, e.g: a=b=c is same as a=(b=c) ►All other operators are left associative: c1+c2+c3 is same as (c1+c2)+c3 May25,2013 COMSATSIntituteofInformation Technology 439
  • 438.
    Operator overloading ►Always writecode representing the operator ►Example: Adding subtraction code inside the + operator will create chaos May25,2013 COMSATSIntituteofInformation Technology 440
  • 439.
    Operator overloading ►Creating anew operator is a syntax error (whether unary, binary or ternary) ► You cannot create $ May25,2013 COMSATSIntituteofInformation Technology 441
  • 440.
    Operator overloading ►Arity ofan operator is NOT affected by overloading ►Example: Division operator will take exactly two operands in any case: b = c / d May25,2013 COMSATSIntituteofInformation Technology 442
  • 441.
    Binary operators ►Binary operatorsact on two quantities ►Binary operators: May25,2013 COMSATSIntituteofInformation Technology 443
  • 442.
    Binary operators ►General syntax: Memberfunction: TYPE1 CLASS::operator B_OP( TYPE2 rhs){ ... } May25,2013 COMSATSIntituteofInformation Technology 444
  • 443.
    Binary operators ►General syntax: Non-memberfunction: TYPE1 operator B_OP(TYPE2 lhs, TYPE3 rhs){ ... } May25,2013 COMSATSIntituteofInformation Technology 445
  • 444.
    Binary operators ►The “operatorOP” must have at least one formal parameter of type class (user defined type) ►Following is an error: int operator + (int, int); May25,2013 COMSATSIntituteofInformation Technology 446
  • 445.
    Binary operators ►Overloading +operator: class Complex{ private: double real, img; public: … Complex operator +(const Complex & rhs); }; May25,2013 COMSATSIntituteofInformation Technology 447
  • 446.
    Binary operators Complex Complex::operator+( const Complex & rhs){ Complex t; t.real = real + rhs.real; t.img = img + rhs.img; return t; } May25,2013 COMSATSIntituteofInformation Technology 448
  • 447.
    Binary operators ►The returntype is Complex so as to facilitate complex statements like: Complex t = c1 + c2 + c3; ►The above statement is automatically converted by the compiler into appropriate function calls: (c1.operator +(c2)).operator +(c3); May25,2013 COMSATSIntituteofInformation Technology 449
  • 448.
    Binary operators ►If thereturn type was void, class Complex{ ... ► public: ► void operator+( ► const Complex & rhs); }; May25,2013 COMSATSIntituteofInformation Technology 450
  • 449.
    Binary operators void Complex::operator+(const Complex& rhs){ real = real + rhs.real; img = img + rhs.img; }; May25,2013 COMSATSIntituteofInformation Technology 451
  • 450.
    Binary operators ►we haveto do the same operation c1+c2+c3 as: c1+c2 c1+c3 // final result is stored in c1 May25,2013 COMSATSIntituteofInformation Technology 452
  • 451.
    Binary operators ►Drawback ofvoid return type: Assignments and cascaded expressions are not possible Code is less readable Debugging is tough Code is very hard to maintain May25,2013 COMSATSIntituteofInformation Technology 453
  • 452.
    References • “Object OrientedProgramming 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 454
  • 453.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 455
  • 454.
    CSC241: Object Oriented Programming Spring 2013 1.Inheritance Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 455.
    Inheritance in Classes •If a class B inherits from class A, then B contains all the characteristics (information structure and behavior) 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 Intitute of Information Technology 457
  • 456.
    UML Notation May 25,2013 COMSATS Intitute of Information Technology 458 Parent Class Child Class Base Class Derived Class
  • 457.
    Inheritance in C++ •There are three types of inheritance in C++ • Public • Private • Protected May 25, 2013 COMSATS Intitute of Information Technology 459
  • 458.
    “IS A” Relationship •IS A relationship is modeled with the help of public inheritance • Syntax class ChildClass : public BaseClass{ ... }; May 25, 2013 COMSATS Intitute of Information Technology 460
  • 459.
    Example class Person{ ... }; class Student:public Person{ ... }; May 25, 2013 COMSATS Intitute of Information Technology 461
  • 460.
    Accessing Members • Publicmembers of base class become public member of derived class • Private members of base class are not accessible from outside of base class, even in the derived class (Information Hiding) May 25, 2013 COMSATS Intitute of Information Technology 462
  • 461.
    Example class Person{ char *name; intage; ... public: const char *GetName() const; int GetAge() const; ... }; May 25, 2013 COMSATS Intitute of Information Technology 463
  • 462.
    Example class Student: publicPerson{ int semester; int rollNo; ... public: int GetSemester() const; int GetRollNo() const; void Print() const; ... }; May 25, 2013 COMSATS Intitute of Information Technology 464
  • 463.
    Example void Student::Print() { cout <<name << “ is in” << “ semester ” << semester; } May 25, 2013 COMSATS Intitute of Information Technology 465 ERROR
  • 464.
    Example void Student::Print() { cout <<GetName() << “ is in semester ” << semester; } May 25, 2013 COMSATS Intitute of Information Technology 466
  • 465.
    Example int main(){ Student stdt; stdt.semester= 0;//error stdt.name = NULL; //error cout << 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 memory as follows May 25, 2013 COMSATS Intitute of Information Technology 468 Data members of base class Data members of derived class base member1 base member2 ... derived member1 derived member2 ...
  • 467.
    Allocation in Memory •Every object of derived class has an anonymous object of base class May 25, 2013 COMSATS Intitute of Information Technology 469
  • 468.
    Constructors • The anonymousobject of base class must be initialized using constructor of base class • When a derived class object is created the constructor of base class is executed before the constructor of derived class May 25, 2013 COMSATS Intitute of Information Technology 470
  • 469.
    Constructors May 25, 2013COMSATS Intitute of Information Technology 471 Base class constructor initializes the anonymous object Derived class constructor initializes the derived class object base member1 base member2 ... derived member1 derived member2 ...
  • 470.
    Example class 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.
    Example int main(){ Child cobj; return0; } May 25, 2013 COMSATS Intitute of Information Technology 473 Output: Parent Constructor... Child Constructor...
  • 472.
    Constructor • If defaultconstructor of base class does not exist then the compiler will try to generate a default constructor for base class and execute it before executing constructor of derived class May 25, 2013 COMSATS Intitute of Information Technology 474
  • 473.
    Constructor •If the userhas given only an overloaded constructor for base class, the compiler will not generate default constructor for base class May 25, 2013 COMSATS Intitute of Information Technology 475
  • 474.
    Example class Parent{ public: Parent(int i){} }; classChild : public Parent{ public: Child(){} } Child_Object; //ERROR May 25, 2013 COMSATS Intitute of Information Technology 476
  • 475.
    Base Class Initializer •C++ has provided a mechanism to explicitly call a constructor of base class from derived class • The syntax is similar to member initializer and is referred as base-class initialization May 25, 2013 COMSATS Intitute of Information Technology 477
  • 476.
    Example class Parent{ public: Parent(int i){…}; }; classChild : public Parent{ public: Child(int i): Parent(i) {…} }; May 25, 2013 COMSATS Intitute of Information Technology 478
  • 477.
    Example class Parent{ public: Parent(){cout << “ParentConstructor...”;} ... }; 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 and member initializer simultaneously May 25, 2013 COMSATS Intitute of Information Technology 480
  • 479.
    Example class 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 after member initializer for derived class • The base class constructor is executed before the initialization of data members of derived class. May 25, 2013 COMSATS Intitute of Information Technology 482
  • 481.
    Initializing Members • Derivedclass can only initialize members of base class using overloaded constructors • Derived class can not initialize the public data member of base class using member initialization list May 25, 2013 COMSATS Intitute of Information Technology 483
  • 482.
    Example class Person{ public: int age; char*name; ... public: Person(); }; May 25, 2013 COMSATS Intitute of Information Technology 484
  • 483.
    Example class Student: publicPerson{ private: int semester; ... public: Student(int a):age(a) { //error } }; May 25, 2013 COMSATS Intitute of Information Technology 485
  • 484.
    Reason • It willbe an assignment not an initialization May 25, 2013 COMSATS Intitute of Information Technology 486
  • 485.
    Destructors • Destructors arecalled in reverse order of constructor called • Derived class destructor is called before the base class destructor is called May 25, 2013 COMSATS Intitute of Information Technology 487
  • 486.
    Example class Parent{ public: Parent(){cout <<“ParentConstructor”;} ~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.
    Example Output: Parent Constructor Child Constructor ChildDestructor Parent Destructor May 25, 2013 COMSATS Intitute of Information Technology 489
  • 488.
    Protected Access Specifier May25, 2013 COMSATS Intitute of Information Technology 490
  • 489.
    Date Classclass Date{ intday, 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(); }; intmain(){ Date aDate; aDate.IsLeapYear(); //Error return 0; }
  • 491.
    Creating SpecialDate Class SpecialDate Date Special Date AddSpecialYear ...
  • 492.
    Creating SpecialDate Class classSpecialDate: 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 Class classDate{ public: ... bool IsLeapYear(); };
  • 495.
    Modified AddSpecialYear void SpecialDate:: AddSpecialYear (int i){ ... if(day == 29 && month == 2 && !IsLeapyear(year+i)){ ... } }
  • 496.
    Protected members • Protectedmembers can not be accessed outside the class • Protected members of base class become protected member of derived class in Public inheritance
  • 497.
    Modified Date Class classDate{ … protected: bool IsLeapYear(); }; int main(){ Date aDate; aDate.IsLeapYear(); //Error return 0; }
  • 498.
    Modified AddSpecialYear void SpecialDate:: AddSpecialYear (int i){ ... if(day == 29 && month == 2 && !IsLeapyear(year+i)){ ... } }
  • 499.
    Disadvantages • Breaks encapsulation •The protected member is part of base class’s implementation as well as derived class’s implementation
  • 500.
    References • “Object OrientedProgramming 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 ,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.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 503
  • 502.
    CSC241: Object Oriented Programming Spring 2013 1.Inheritance Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 503.
    Hierarchy of Inheritance •We represent the classes involved in inheritance relation in tree like hierarchy May 25, 2013 COMSATS Intitute of Information Technology 505
  • 504.
    Example May 25, 2013COMSATS Intitute of Information Technology 506 GrandParent Parent1 Parent2 Child1 Child2
  • 505.
    Direct Base Class •Adirect base class is explicitly listed in a derived class's header with a colon (:) class Child1:public Parent1 ... May 25, 2013 COMSATS Intitute of Information Technology 507
  • 506.
    Indirect Base Class •Anindirect base class is not explicitly listed in a derived class's header with a colon (:) •It is inherited from two or more levels up the hierarchy of inheritance class GrandParent{}; class Parent1: public GrandParent {}; class Child1:public Parent1{}; May 25, 2013 COMSATS Intitute of Information Technology 508
  • 507.
    Base Initialization • Thechild can only perform the initialization of direct base class through base class initialization list • The child can not perform the initialization of an indirect base class through base class initialization list May 25, 2013 COMSATS Intitute of Information Technology 509
  • 508.
    Example class 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.
    Example class Parent1: publicGrandParent{ int pData; public: Parent1() : GrandParent(), pData(0) {…} }; May 25, 2013 COMSATS Intitute of Information Technology 511
  • 510.
    Example class 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 classcan override the function of GrandParent class May 25, 2013 COMSATS Intitute of Information Technology 513
  • 512.
    Example May 25, 2013COMSATS Intitute of Information Technology 514 GrandParent Print() Parent1 Child1 Print()
  • 513.
    Example void GrandParent::Print() { cout<< “GrandParent::Print” << endl; } void Child1::Print() { cout << “Child1::Print” << endl; } May 25, 2013 COMSATS Intitute of Information Technology 515
  • 514.
  • 515.
    Output • Output isas follows Child1::Print GrandParent::Print GrandParent::Print May 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 specify the type of inheritance May 25, 2013 COMSATS Intitute of Information Technology 518
  • 517.
    Public Inheritance Member accessin Base Class Derived Class Public Public Protected Protected Private Hidden class Child: public Parent {…};
  • 518.
    Protected Inheritance Member accessin Base Class Derived Class Public Protected Protected Protected Private Hidden class Child: protected Parent {…};
  • 519.
    Private Inheritance Member accessin Base Class Derived Class Public Private Protected Private Private Hidden class Child: private Parent {…};
  • 520.
    Private Inheritance • Ifthe user does not specifies the type of inheritance then the default type is private inheritance class Child: private Parent {…} is equivalent to class Child: Parent {…} May 25, 2013 COMSATS Intitute of Information Technology 522
  • 521.
    Private Inheritance • Weuse private inheritance when we want to reuse code of some class • Private Inheritance is used to model “Implemented in terms of” relationship May 25, 2013 COMSATS Intitute of Information Technology 523
  • 522.
    Example class Collection { ... public: voidAddElement(int); bool SearchElement(int); bool SearchElementAgain(int); bool DeleteElement(int); }; May 25, 2013 COMSATS Intitute of Information Technology 524
  • 523.
    Example • If elementis not found in the Collection the function SearchElement will return false • SearchElementAgain finds the second instance of element in the collection May 25, 2013 COMSATS Intitute of Information Technology 525
  • 524.
    Class Set class 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 Set void Set::AddMember(inti){ 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 OrientedProgramming 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 ,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.
    Thanks May 25, 2013COMSATS Intitute of Information Technology 529
  • 528.
    CSC241: Object Oriented Programming Spring 2013 1.Private Inheritance 2. Specialization Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 529.
    Private Inheritance • Ifthe user does not specifies the type of inheritance then the default type is private inheritance class Child: private Parent {…} is equivalent to class Child: Parent {…} May 25, 2013 COMSATS Intitute of Information Technology
  • 530.
    Private Inheritance • Weuse private inheritance when we want to reuse code of some class • Private Inheritance is used to model “Implemented in terms of” relationship May 25, 2013 COMSATS Intitute of Information Technology
  • 531.
    Example class Collection { ... public: voidAddElement(int); bool SearchElement(int); bool SearchElementAgain(int); bool DeleteElement(int); }; May 25, 2013 COMSATS Intitute of Information Technology
  • 532.
    Example • If elementis not found in the Collection the function SearchElement will return false • SearchElementAgain finds the second instance of element in the collection May 25, 2013 COMSATS Intitute of Information Technology
  • 533.
    Class Set class Set:private Collection { private: ... public: void AddMember(int); bool IsMember(int); bool DeleteMember(int); }; May 25, 2013 COMSATS Intitute of Information Technology
  • 534.
    Class Set void Set::AddMember(inti){ if (! IsMember(i) ) AddElement(i); } bool Set::IsMember(int i){ return SearchElement(i); } May 25, 2013 COMSATS Intitute of Information Technology
  • 535.
    Specialization (Restriction) • thederived 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 Intitute of Information Technology
  • 536.
    Specialization (Restriction) • Specialization(Restriction) can be implemented using private and protected inheritance May 25, 2013 COMSATS Intitute of Information Technology
  • 537.
    Example – Specialization (Restriction) May25,2013 COMSATSIntituteofInformation Technology Person age: [0..125] Adult age : [18..125] setAge( a ) setAge( a ) age = a If age < 18 then error else age = a
  • 538.
    Private Inheritance Member accessin Base Class Derived Class Public Private Protected Private Private Hidden class Child: private Parent {…};
  • 539.
    Exampleclass Person{ … protected: int age; public: boolSetAge(int _age){ if (_age >=0 && _age <= 125) { age = _age; return true; } return false; } };May 25, 2013 COMSATS Intitute of Information Technology
  • 540.
    Example class 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 functionality to an existing class. Now let’s look at an example where inheritance is used for a different purpose: as part of the original design of a program. • Our example models a database of employees of a widget company. We’ve simplified the situation so that only three kinds of employees are represented. Managers manage, scientists perform research to develop better widgets, and laborers operate the dangerous widget- stamping presses. • The database stores a name and an employee identification number for all employees, no matter what their category. However, for managers, it also stores their titles and golf club dues. For scientists, it stores the number of scholarly articles they have published. Laborers need no additional data beyond their names and numbers. • Our example program starts with a base class employee. This class handles the employee’s last name and employee number. From this class three other classes are derived: manager, scientist, and laborer. The manager and scientist classes contain additional information about these categories of employee, and member functions to handle this information, as shown in Figure May 25, 2013 COMSATS Intitute of Information Technology
  • 542.
    May 25, 2013COMSATS Intitute of Information Technology
  • 543.
    Exercise 1 • Imaginea publishing company that markets both book and audiocassette versions of its works. Create a class publication that stores the title (a string) and price (type float) of a publication. From this class derive two classes: book, which adds a page count (type int), and tape, which adds a playing time in minutes (type float). Each of these three classes should have a getdata() function to get its data from the user at the keyboard, and a putdata() function to display its data. Write a main() program to test the book and tape classes by creating instances of them, asking the user to fill in data with getdata(), and then displaying the data with putdata(). May 25, 2013 COMSATS Intitute of Information Technology
  • 544.
    Exercise 2 • Startwith the publication, book, and tape classes of Exercise 1. Add a base class sales that holds an array of three floats so that it can record the 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 book and tape classes so they are derived from both publication and sales. An object of class book or tape should input and output sales data along with its other data. Write a main() function to create a book object and a tape object and exercise their input/output capabilities. May 25, 2013 COMSATS Intitute of Information Technology
  • 545.
    Exercise 3 • Assumethat the publisher in Exercises 1 and 3 decides to add a third way to distribute books: on computer disk, for those who like to do their reading on their laptop. Add a disk class that, like book and tape, is derived from publication. The disk class should incorporate the same member functions as the other classes. The data item unique to this class is the disk type: either CD or DVD. You can use an enum type to store this item. The user could select the appropriate type by typing c or d. May 25, 2013 COMSATS Intitute of Information Technology
  • 546.
    References • “Object OrientedProgramming 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 ,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.
    Thanks May 25, 2013COMSATS Intitute of Information Technology
  • 548.
    CSC241: Object Oriented Programming Spring 2013 1.Overriding & Overloading 2. Multiple Inheritance 3. Virtual Inheritance 4. Virtual Functions/Members Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 549.
    Overriding Member Functionsof Base Class • Derived class can override the member functions of its base class • To override a function the derived class simply provides a function with the same signature as that of its base class May 25, 2013 COMSATS Institute of Information Technology 553
  • 550.
    Overriding May 25, 2013COMSATS Institute of Information Technology 554 Parent ... Func1 Child ... Func1
  • 551.
    Overriding class Parent { public: voidFunc1(); voidFunc1(int); }; classChild: 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 duplicate declaration May 25, 2013 COMSATS Institute of Information Technology 556
  • 553.
    Overriding class Parent { public: voidFunc1(); void Func1(); //Error }; May 25, 2013 COMSATS Institute of Information Technology 557
  • 554.
    Overriding Member Functionsof Base Class • Derive class can override member function of base class such that the working of function is totally changed May 25, 2013 COMSATS Institute of Information Technology 558
  • 555.
    Example class Person{ public: void Walk(); }; classParalyzedPerson: public Person{ public: void Walk(); }; May 25, 2013 COMSATS Institute of Information Technology 559
  • 556.
    Overriding Member Functionsof Base Class • Derive class can override member function of base class such that the working of function is similar to former implementation May 25, 2013 COMSATS Institute of Information Technology 560
  • 557.
    Example class 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.
    Example class 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.
    Example int main(){ Student a(“Ahmad”,“Computer Science”); a.Print(); return 0; } May 25, 2013 COMSATS Institute of Information Technology 563
  • 560.
    Output Output: Name: Ahmed Major: ComputerScience May 25, 2013 COMSATS Institute of Information Technology 564
  • 561.
    Overriding Member Functionsof Base Class • Derive class can override member function of base class such that the working of function is based on former implementation May 25, 2013 COMSATS Institute of Information Technology 565
  • 562.
    Example class Student :public Person{ char * major; public: Student(char * aName, char* m); void Print(){ Print();//Print of Person cout<<“Major:” << major <<endl; } ... }; May 25, 2013 COMSATS Institute of Information Technology 566
  • 563.
    Example int main(){ Student a(“Ahmad”,“Computer Science”); a.Print(); return 0; } May 25, 2013 COMSATS Institute of Information Technology 567
  • 564.
    Output • There willbe no output as the compiler will call the print of the child class from print of child class recursively • There is no ending condition May 25, 2013 COMSATS Institute of Information Technology 568
  • 565.
    Example class 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.
    Example int main(){ Student a(“Ahmad”,“Computer Science”); a.Print(); return 0; } May 25, 2013 COMSATS Institute of Information Technology 570
  • 567.
    Output Output: Name: Ahmed Major: ComputerScience May 25, 2013 COMSATS Institute of Information Technology 571
  • 568.
    {Before New Topic……} •I need Your anonymous Feed Back • About the Instructor •& • About the Course May 25, 2013 COMSATS Institute of Information Technology 572
  • 569.
    Multiple Inheritance • Aclass can inherit from more then one class May 25, 2013 COMSATS Institute of Information Technology 573
  • 570.
    Multiple Inheritance May 25,2013 COMSATS Institute of Information Technology 574 Transmitter ... Transmit() Receiver ... Receive() Phone
  • 571.
    Example class Phone: publicTransmitter, public Receiver { ... }; May 25, 2013 COMSATS Institute of Information Technology 575
  • 572.
    Multiple Inheritance • Derivedclass can inherit from public base class as well as private and protected base classes class Mermaid: private Woman, private Fish May 25, 2013 COMSATS Institute of Information Technology 576
  • 573.
    Multiple Inheritance • Thederived class inherits data members and functions form all the base classes • Object of derived class can perform all the tasks that an object of base class can perform May 25, 2013 COMSATS Institute of Information Technology 577
  • 574.
    Example int main(){ Phone obj; obj.Transmit(); obj.Receive(); return0; } May 25, 2013 COMSATS Institute of Information Technology 578
  • 575.
    Multiple Inheritance • Whenusing public multiple inheritance, the object of derived class can replace the objects of all the base classes May 25, 2013 COMSATS Institute of Information Technology 579
  • 576.
    Example int main(){ Phone obj; Transmitter* tPtr = &obj; Receiver * rPtr = &obj; return 0; } May 25, 2013 COMSATS Institute of Information Technology 580
  • 577.
    Multiple Inheritance • Thepointer of one base class cannot be used to call the function of another base class • The functions are called based on static type May 25, 2013 COMSATS Institute of Information Technology 581
  • 578.
    Example int main(){ Phone obj; Transmitter* tPtr = &obj; tPtr->Transmit(); tPtr->Receive(); //Error return 0; } May 25, 2013 COMSATS Institute of Information Technology 582
  • 579.
    Example int main(){ Phone obj; Receiver* rPtr = &obj; rPtr->Receive(); rPtr->Transmit(); //Error return 0; } May 25, 2013 COMSATS Institute of Information Technology 583
  • 580.
    Multiple Inheritance • Ifmore than one base class have a function with same signature then the child will have two copies of that function • Calling such function will result in ambiguity May 25, 2013 COMSATS Institute of Information Technology 584
  • 581.
    Multiple Inheritance May 25,2013 COMSATS Institute of Information Technology 585 Amphibious Vehicle Land Vehicle Water Vehicle Car Boat
  • 582.
    Example class LandVehicle{ public: int GetMaxLoad(); }; classWaterVehicle{ public: int GetMaxLoad(); }; May 25, 2013 COMSATS Institute of Information Technology 586
  • 583.
    Example class AmphibiousVehicle: public LandVehicle, publicWaterVehicle{ }; int main(){ AmphibiousVehicle obj; obj.GetMaxLoad(); // Error return 0; } May 25, 2013 COMSATS Institute of Information Technology 587
  • 584.
    Multiple Inheritance • Programmermust explicitly specify the class name when calling ambiguous function May 25, 2013 COMSATS Institute of Information Technology 588
  • 585.
  • 586.
    Multiple Inheritance • Theambiguous call problem can arise when dealing with multiple level of multiple inheritance May 25, 2013 COMSATS Institute of Information Technology 590
  • 587.
    Multiple Inheritance May 25,2013 COMSATS Institute of Information Technology 591 Amphibious Vehicle Land Vehicle Water Vehicle Vehicle Car Boat
  • 588.
    Example class Vehicle{ public: int GetMaxLoad(); }; classLandVehicle : public Vehicle{ }; class WaterVehicle : public Vehicle{ }; May 25, 2013 COMSATS Institute of Information Technology 592
  • 589.
    Example class AmphibiousVehicle: public LandVehicle, publicWaterVehicle{ }; int main(){ AmphibiousVehicle obj; obj.GetMaxLoad(); // Error return 0; } May 25, 2013 COMSATS Institute of Information Technology 593
  • 590.
    Example int main() { AmphibiousVehicle obj; obj.Vehicle::GetMaxLoad();//Error return 0; } •Vehicle is accessible through two paths May 25, 2013 COMSATS Institute of Information Technology 594
  • 591.
    Multiple Inheritance May 25,2013 COMSATS Institute of Information Technology 595 Amphibious Vehicle Land Vehicle Water Vehicle Vehicle Car Boat Vehicle
  • 592.
  • 593.
    Multiple Inheritance • Datamember must be used with care when dealing with more then one level on inheritance May 25, 2013 COMSATS Institute of Information Technology 597
  • 594.
    Example class Vehicle{ protected: int weight; }; classLandVehicle : public Vehicle{ }; class WaterVehicle : public Vehicle{ }; May 25, 2013 COMSATS Institute of Information Technology 598
  • 595.
    Example class AmphibiousVehicle: public LandVehicle, publicWaterVehicle{ public: AmphibiousVehicle(){ LandVehicle::weight = 10; WaterVehicle::weight = 10; } }; • There are multiple copies of data member weight May 25, 2013 COMSATS Institute of Information Technology 599
  • 596.
    Memory View May25,2013 COMSATSInstituteofInformation Technology 600 Data Membersof Vehicle Data Members of LandVehicle Data Members of AmphibiousVehicle Data Members of Vehicle Data Members of WaterVehicle
  • 597.
    Virtual Inheritance • Invirtual inheritance there is exactly one copy of the anonymous base class object May 25, 2013 COMSATS Institute of Information Technology 601
  • 598.
    Example class Vehicle{ protected: int weight; }; classLandVehicle : public virtual Vehicle{ }; class WaterVehicle : public virtual Vehicle{ }; May 25, 2013 COMSATS Institute of Information Technology 602
  • 599.
    Example class AmphibiousVehicle: public LandVehicle, publicWaterVehicle{ public: AmphibiousVehicle(){ weight = 10; } }; May 25, 2013 COMSATS Institute of Information Technology 603
  • 600.
    Memory View May 25,2013 COMSATS Institute of Information Technology 604 Data Members of Vehicle Data Members of LandVehicle Data Members of AmphibiousVehicle Data Members of WaterVehicle
  • 601.
    Virtual Inheritance • Virtualinheritance must be used when necessary • There are situation when programmer would want to use two distinct data members inherited from base class rather then one May 25, 2013 COMSATS Institute of Information Technology 605
  • 602.
    Example May 25, 2013COMSATS Institute of Information Technology 606 Student BS Student MS Student PhD Student MS/PhD Student GPA
  • 603.
    References • “Object OrientedProgramming 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 ,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.
    Thanks May 25, 2013COMSATS Institute of Information Technology 608
  • 605.
    CSC241: Object Oriented Programming Spring 2013 1.Generic Programming 2. Templates Please turn OFF your Mobile Phones! Saturday, May 25, 2013 Farhan Aadil
  • 606.
    Quiz • Explain “Diamondof Death” with help of Class Diagram, also write code for your class diagram. May 25, 2013 COMSATS Institute of Information Technology 610
  • 607.
    Feed Back • Highlevel 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 functionprints an array of integer elements: void printArray(int* array, int size) { for ( int i = 0; i < size; i++ ) cout << array[ i ] << “, ”; }
  • 610.
    ...Motivation • What ifwe 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 ifwe 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 ifwe want to change the way function prints the array. e.g. from 1, 2, 3, 4, 5 to 1 - 2 - 3 - 4 - 5
  • 613.
    ...Motivation • Now considerthe Array class that wraps an array of integers class Array { int* pArray; int size; public: … };
  • 614.
    ...Motivation • What ifwe want to use an Array class that wraps arrays of double? class Array { double* pArray; int size; public: … };
  • 615.
    ...Motivation • What ifwe want to use an Array class that wraps arrays of boolean variables? class Array { bool* pArray; int size; public: … };
  • 616.
    ...Motivation • Now ifwe want to add a function sum to Array class, we have to change all the three classes
  • 617.
    Generic Programming • Genericprogramming refers to programs containing generic abstractions • A generic program abstraction (function, class) can be parameterized with a type • Such abstractions can work with many different types of data
  • 619.
  • 620.
    Templates • In C++generic programming is done using templates • Two kinds • Function Templates • Class Templates • Compiler generates different type-specific copies from a single template
  • 621.
    Function Templates • Afunction template can be parameterized to operate on different types of data
  • 622.
    Declaration template< class T> void funName( T x ); // OR template< typename T > void funName( T x ); // OR template< class T, class U, … > void funName( T x, U y, … );
  • 623.
    Example – FunctionTemplates • Following function template prints an array having almost any type of elements: template< typename T > void printArray( T* array, int size ) { for ( int i = 0; i < size; i++ ) cout << array[ i ] << “, ”; }
  • 624.
    …Example – FunctionTemplates int 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; }
  • 625.
    Explicit Type Parameterization •A function template may not have any parameter template <typename T> T getInput() { T x; cin >> x; return x; }
  • 626.
    …Explicit Type Parameterization intmain() { int x; x = getInput(); // Error! double y; y = getInput(); // Error! }
  • 627.
    …Explicit Type Parameterization intmain() { int x; x = getInput< int >(); double y; y = getInput< double >(); }
  • 628.
    User-defined Specializations • Atemplate may not handle all the types successfully • Explicit specializations need to be provided for specific type(s)
  • 629.
    Example – UserSpecializations template< typename T > bool isEqual( T x, T y ) { return ( x == y ); }
  • 630.
    … Example –User Specializations int main { isEqual( 5, 6 );// OK isEqual( 7.5, 7.5 ); // OK isEqual( “abc”, “xyz” ); // Logical Error! return 0; }
  • 631.
    … Example –User Specializations template< > bool isEqual< const char* >( const char* x, const char* y ) { return ( strcmp( x, y ) == 0 ); }
  • 632.
    … Example –User Specializations int main { isEqual( 5, 6 ); // Target: general template isEqual( 7.5, 7.5 ); // Target: general template isEqual( “abc”, “xyz” ); // Target: user specialization return 0; }
  • 633.
    References • “Object OrientedProgramming 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 ,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
  • 634.
    Thanks May 25, 2013COMSATS Institute of Information Technology 638
  • 635.
    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; • }
  • 636.
    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): ";