Download - All in 1
CSC241:Object Oriented ProgrammingSpring 2013
1. Starting OOP
April
10,
202
3CO
MSA
TS In
stitu
te o
f Inf
orm
ation
Tec
hnol
ogy
2
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan Aadil
10 April 2023 COMSATS Institute of Information Technology 3
Study Assignment
• I hope you did go through chapter 1 of both the books.• How was the experience?• What did you learn?
10 April 2023 COMSATS Institute of Information Technology 4
Procedural vs. Object-Oriented
• Procedural
Withdraw, deposit, transfer
• Object Oriented
Customer, money, account
What is Object-Orientation?
• A technique for system modeling
• OO model consists of several interacting objects
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 7
Examples – Model
• Highway maps
• Architectural models
• Mechanical models
April 10, 2023 COMSATS Institute of Information Technology 8
…Example – OO Model• Objects
• Ali• House• Car• Tree
• Interactions• Ali lives in the house• Ali drives the car
April 10, 2023 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
April 10, 2023 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)
April 10, 2023 COMSATS Institute of Information Technology 12
… What is an Object?
An object has
• State (attributes)• Well-defined behaviour (operations)• Unique identity
April 10, 2023 COMSATS Institute of Information Technology 13
Example – Ali is a Tangible Object
• State (attributes)• Name• Age
• behaviour (operations)• Walks• Eats
• Identity• His name
April 10, 2023 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
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 17
10 April 2023 COMSATS Institute of Information Technology 18
Definition
• What Is an Object? • An object is a software bundle of related variables and methods.
Software objects are often used to model real-world objects you find in everyday life.
• Objects are key to understanding object-oriented technology. You can look around you now and see many examples of real-world objects: dog, desk, television set, bicycle.
10 April 2023 COMSATS Institute of Information Technology 19
Real-world objects share two characteristics • They all have state and behavior • dogs have state (name, color, breed, hungry) and behavior (barking,
fetching, and wagging tail). • Bicycles have state (current gear, current pedal cadence, two wheels,
number of gears) and behavior (braking, accelerating, slowing down, changing gears).
10 April 2023 COMSATS Institute of Information Technology 20
Software objects are modeled after real-world objects • A software object maintains its state in one or more variables . • A software object implements its behavior with methods . A method
is a function (subroutine) associated with an object.
10 April 2023 COMSATS Institute of Information Technology 21
Can represent real-world objects by using software objects. • You might want to represent real-world dogs as software objects in an
animation program or a real-world bicycle as a software object in the program that controls an electronic exercise bike.
• You can also use software objects to model abstract concepts. For example, an event is a common object used in GUI window systems to represent the action of a user pressing a mouse button or a key on the keyboard.
10 April 2023 COMSATS Institute of Information Technology 22
Moving to new thinking …
• C is a procedural language. A procedure is a list of instructions.
• Very small programs (tens of lines) need no organization.• As they get large (hundreds of lines), they are divided into
functions.• Functions are still lists of instructions.• Dividing a program into functions gives a structure to the
program (hence structured programming).
10 April 2023 COMSATS Institute of Information Technology 23
Moving to new thinking …
• C programming cannot do the following well:• Functions have unrestricted access to global data.• Data and Functions are unrelated; they do not form a
logical group or show any form of binding.• Cannot model ‘real world’.
• In real world, we deal with objects like cars, people etc.
• Are such objects like ‘data’? Which data type describes a car, for example?
• Are such objects like ‘functions’? What will a function car() do?
10 April 2023 COMSATS Institute of Information Technology 24
Moving to new thinking …• A real world object, e.g. car:
• Is its description purely the ability to have a ‘data type’ to represent its specifications or ‘attributes’ only? For example what attributes describe a car?
• So by having all these attributes ‘only’ do you know all about a car? Would you buy a car by merely looking at these attributes and their values?
• No! What else do you wish to have?
10 April 2023 COMSATS Institute of Information Technology 25
Moving to new thinking …• A real world object, e.g. car:
• Test drive! Right?• What would you know through a test drive: how it
‘behaves’ in response to various stimulus!• How can it negotiate a speed braker, a speedy turn, full braking
etc.• Effectively, you wish to know how it ‘functions’.• Behaviour is like a function.
• So neither data nor functions, by themselves, model real-world objects effectively.
10 April 2023 COMSATS Institute of Information Technology 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.
10 April 2023 COMSATS Institute of Information Technology 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.
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”
April 10, 2023 COMSATS Institute of Information Technology 28
Example – Abstraction
• Attributes- Name - Employee ID- Student Roll No - Designation- Year of Study - Salary- CGPA - Age
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 31
Student’s Perspective
Example – Abstraction
• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - Walk
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 33
Teacher’s Perspective
Example – Abstraction
• behaviour- Study - DevelopExam- GiveExam - TakeExam- PlaySports - Eat- DeliverLecture - Walk
April 10, 2023 COMSATS Institute of Information Technology 34
Teacher’s Perspective
Example – Abstraction
• Ordinary PerspectiveA pet animal with• Four Legs• A Tail• Two Ears• Sharp Teeth
• Surgeon’s PerspectiveA being with• A Skeleton• Heart• Kidney• Stomach
April 10, 2023 COMSATS Institute of Information Technology 35
A cat can be viewed with different perspectives
Example – Abstraction
April 10, 2023 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
April 10, 2023 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
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 40
Graphical Representation of Classes
April 10, 2023 COMSATS Institute of Information Technology 41
(Class Name)
(attributes)
(operations)
(Class Name)
Normal Form
Suppressed Form
Example – Graphical Representation of Classes
April 10, 2023 COMSATS Institute of Information Technology 42
CirclecenterradiusdrawcomputeArea
Normal Form
Suppressed Form
Circle
Example – Graphical Representation of Classes
April 10, 2023 COMSATS Institute of Information Technology 43
Personnameagegendereatwalk
Normal Form
Suppressed Form
Person
Inheritance
• A child inherits characteristics of its parents
• Besides inherited characteristics, a child may have its own unique characteristics
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 45
Example – Inheritance
April 10, 2023 COMSATS Institute of Information Technology 46
Person
TeacherDoctorStudent
Example – Inheritance
April 10, 2023 COMSATS Institute of Information Technology 47
Shape
CircleTriangleLine
Inheritance – “IS A” or“IS A KIND OF” Relationship
• Each derived class is a special kind of its base class
April 10, 2023 COMSATS Institute of Information Technology 48
Example – “IS A” Relationship
April 10, 2023 COMSATS Institute of Information Technology 49
Personnameagegendereatwalk
TeacherdesignationsalaryteachtakeExam
StudentprogramstudyYearstudyheldExam
DoctordesignationsalarycheckUpprescribe
Example – “IS A” Relationship
April 10, 2023 COMSATS Institute of Information Technology 50
ShapecolorcoorddrawrotatesetColor
CircleradiusdrawcomputeArea
Linelengthdraw
TriangleangledrawcomputeArea
Inheritance – Advantages
• Reuse
• Less redundancy
• Increased maintainability
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 52
Example Reuse
April 10, 2023 COMSATS Institute of Information Technology 53
ShapecolorcoorddrawrotatesetColor
CircleradiusdrawcomputeArea
Linelengthdraw
TriangleangledrawcomputeArea
Example Reuse
April 10, 2023 COMSATS Institute of Information Technology 54
Personnameagegendereatwalk
TeacherdesignationsalaryteachtakeExam
StudentprogramstudyYearstudyheldExam
DoctordesignationsalarycheckUpprescribe
Example Reuse
April 10, 2023 COMSATS Institute of Information Technology 55
Personnameagegendereatwalk
TeacherdesignationsalaryteachtakeExam
StudentprogramstudyYearstudyheldExam
DoctordesignationsalarycheckUpprescribe
56
References
• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (The Waite Group). 4th ed. available in soft form.
• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology, Cengage Learning. 4th ed. available in soft form
• National University of Computer & Emerging Sciences [www.nu.edu.pk]
• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
April
10,
202
3CO
MSA
TS In
stitu
te o
f Inf
orm
ation
Tec
hnol
ogy
CSC241:Object Oriented ProgrammingSpring 2013
1. Inheritance & Generalization
April
10,
202
3CO
MSA
TS In
stitu
te o
f Inf
orm
ation
Tec
hnol
ogy
58
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan 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
April 10, 2023 COMSATS Institute of Information Technology 59
Concepts Related with Inheritance
• Generalization
• Subtyping (extension)
• Specialization (restriction)
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 61
Example – Generalization
April 10, 2023 COMSATS Institute of Information Technology 62
CirclecolorverticesradiusmovesetColorcomputeArea
LinecolorverticeslengthmovesetColorgetLength
TrianglecolorverticesanglemovesetColorcomputeArea
Example – Generalization
April 10, 2023 COMSATS Institute of Information Technology 63
ShapecolorverticesmovesetColor
CircleradiuscomputeArea
LinelengthgetLength
TriangleanglecomputeArea
Example – Generalization
April 10, 2023 COMSATS Institute of Information Technology 64
TeachernameagegenderdesignationsalaryteachtakeExameatwalk
StudentnameagegenderprogramstudyYearstudyheldExameatwalk
DoctornameagegenderdesignationsalarycheckUpprescribeeatwalk
Example – Generalization
April 10, 2023 COMSATS Institute of Information Technology 65
Personnameagegendereatwalk
TeacherdesignationsalaryteachtakeExam
StudentprogramstudyYearstudyheldExam
DoctordesignationsalarycheckUpprescribe
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
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 67
Example –Sub-typing (Extension)
April 10, 2023 COMSATS Institute of Information Technology 68
Personnameagegendereatswalks
StudentprogramstudyYearstudytakeExam
Example – Sub-typing (Extension)
April 10, 2023 COMSATS Institute of Information Technology 69
ShapecolorverticessetColormove
CircleradiuscomputeCFcomputeArea
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
April 10, 2023 COMSATS Institute of Information Technology 70
Example – Specialization (Restriction)
April 10, 2023 COMSATS Institute of Information Technology 71
Personage : [0..100]…
Adultage : [18..100]…
setAge( a )…
setAge( a )…
age = a
If age < 18 then errorelse age = a
Example – Specialization (Restriction)
April 10, 2023 COMSATS Institute of Information Technology 72
IntegerSet…
NaturalSet…
add( elem )…
add( elem )…
add element to the set
If elem < 1 then errorelse
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
April 10, 2023 COMSATS Institute of Information Technology 73
Example – Specific Behaviour
April 10, 2023 COMSATS Institute of Information Technology 74
ShapecolorverticesdrawmovesetColor
CircleradiusdrawcomputeArea
Linelengthdraw
TriangleangledrawcomputeArea
Example – Extension
April 10, 2023 COMSATS Institute of Information Technology 75
Windowwidthheightopenclosedraw
DialogBoxcontrolsenabledraw
1- Invoke Window’s draw2- draw the dialog box
Example – Restriction
April 10, 2023 COMSATS Institute of Information Technology 76
IntegerSet…
NaturalSet…
add( elem )…
add( elem )…
Add element to the set
If elem < 1 then give errorelse
Add element to the set
April 10, 2023 COMSATS Institute of Information Technology 77
Example – Improve Performance
• Class Circle overrides rotate operation of class Shape with a Null operation.
ShapecolorcoorddrawrotatesetColor
Circleradiusdrawrotate
Abstract Classes
• An abstract class implements an abstract concept• Main purpose is to be inherited by other classes• Can’t be instantiated• Promotes reuse
April 10, 2023 COMSATS Institute of Information Technology 78
Example – Abstract Classes
• Here, Person is an abstract classApril 10, 2023 COMSATS Institute of Information Technology 79
TeacherDoctorStudent
Personnameagegendereatwalk
Example – Abstract Classes
• Here, Vehicle is an abstract classApril 10, 2023 COMSATS Institute of Information Technology 80
BusTruckCar
VehiclecolormodelaccelerateapplyBrakes
Concrete Classes
• A concrete class implements a concrete concept
• Main purpose is to be instantiated
• Provides implementation details specific to the domain context
April 10, 2023 COMSATS Institute of Information Technology 81
Example – Concrete Classes
• Here, Student, Teacher and Doctor are concrete classesApril 10, 2023 COMSATS Institute of Information Technology 82
TeacherDoctorStudent
programstudyYearstudyheldExam
Person
Example – Concrete Classes
April 10, 2023 COMSATS Institute of Information Technology 83
• Here, Car, Bus and Truck are concrete classes
BusCar
Vehicle
Truckcapacityloadunload
Multiple Inheritance
• We may want to reuse characteristics of more than one parent class
April 10, 2023 COMSATS Institute of Information Technology 84
Example – Multiple Inheritance
April 10, 2023 COMSATS Institute of Information Technology 86
Mermaid
Woman Fish
Example – Multiple Inheritance
April 10, 2023 COMSATS Institute of Information Technology 87
Amphibious Vehicle
Example – Multiple Inheritance
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 89
Problem – Duplicate Features
• Which eat operation Mermaid inherits?
April 10, 2023 COMSATS Institute of Information Technology 90
Mermaid
Woman Fisheat…
eat…
Solution – Override the Common Feature
April 10, 2023 COMSATS Institute of Information Technology 91
Mermaid
Woman Fisheat…
eat…
eat…
Invoke eat operation of desired class
Problem – Duplicate Features (Diamond Problem)
• Which changeGear operation Amphibious Vehicle inherits?
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 94
Kinds of Association
• Class Association• Inheritance
• Object Association• Simple Association• Composition• Aggregation
April 10, 2023 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”
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 98
Example – Association
• Ali lives in a House
April 10, 2023 COMSATS Institute of Information Technology 99
Ali Houselives-in11
Example – Association
• Ali drives his Car
April 10, 2023 COMSATS Institute of Information Technology 100
Ali Cardrives*1
Two-way Association
• We can navigate in both directions
• Denoted by a line between the associated objects
April 10, 2023 COMSATS Institute of Information Technology 101
Example – Two-way Association
• Employee works for company• Company employs employees
April 10, 2023 COMSATS Institute of Information Technology 102
Employee Companyworks-for1*
Example – Two-way Association
• Yasir is a friend of Ali• Ali is a friend of Yasir
April 10, 2023 COMSATS Institute of Information Technology 103
Yasir Alifriend11
Binary Association
• Associates objects of exactly two classes
• Denoted by a line, or an arrow between the associated objects
April 10, 2023 COMSATS Institute of Information Technology 104
Example – Binary Association
• Association “works-for” associates objects of exactly two classes
April 10, 2023 COMSATS Institute of Information Technology 105
Employee Companyworks-for1*
Example – Binary Association
• Association “drives” associates objects of exactly two classes
April 10, 2023 COMSATS Institute of Information Technology 106
Ali Cardrives*1
Ternary Association
• Associates objects of exactly three classes
• Denoted by a diamond with lines connected to associated objects
April 10, 2023 COMSATS Institute of Information Technology 107
Example – Ternary Association
• Objects of exactly three classes are associated
April 10, 2023 COMSATS Institute of Information Technology 108
Student Teacher
Course
1
*
*
Example – Ternary Association
• Objects of exactly three classes are associated
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 111
Example – Composition of Ali
April 10, 2023 COMSATS Institute of Information Technology 112
Ali
Body
Arm
Head
Leg
1
1
2 2
Example – Composition of Chair
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 115
Example – Composition is Stronger
• Chair’s body is made up of different parts
• They can’t exist independently
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 117
Example – Aggregation
April 10, 2023 COMSATS Institute of Information Technology 118
Room
Cupboard
Bed
Chair Table*
1
1
1
Aggregation is Weaker
• Aggregation is weaker relationship, because• Aggregate object is not a part of the container• Aggregate object can exist independently
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 122
123
References
• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (The Waite Group). 4th ed. available in soft form.
• “Object Oriented Programming Using C++” by “Joyce Farrell” , published by Course Technology, Cengage Learning. 4th ed. available in soft form
• National University of Computer & Emerging Sciences [www.nu.edu.pk]
• Virtual University of Pakistan [ocw.vu.edu.pk]• Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
April
10,
202
3CO
MSA
TS In
stitu
te o
f Inf
orm
ation
Tec
hnol
ogy
CSC241:Object Oriented ProgrammingSpring 2013
1. Inheritance Concepts2. Polymorphism
April 10, 2023 COMSATS Intitute of Information Technology
125
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan Aadil
126
Class diagram showing inheritance
April 10, 2023 COMSATS Intitute of Information Technology
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
April 10, 2023 COMSATS Intitute of Information Technology 127
Kinds of Association
• Class Association• Inheritance
• Object Association• Simple Association• Composition• Aggregation
April 10, 2023 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”
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 131
Example – Association
• Ali lives in a House
April 10, 2023 COMSATS Intitute of Information Technology 132
Ali Houselives-in11
Example – Association
• Ali drives his Car
April 10, 2023 COMSATS Intitute of Information Technology 133
Ali Cardrives*1
Two-way Association
• We can navigate in both directions
• Denoted by a line between the associated objects
April 10, 2023 COMSATS Intitute of Information Technology 134
Example – Two-way Association
• Employee works for company• Company employs employees
April 10, 2023 COMSATS Intitute of Information Technology 135
Employee Companyworks-for1*
Example – Two-way Association
• Yasir is a friend of Ali• Ali is a friend of Yasir
April 10, 2023 COMSATS Intitute of Information Technology 136
Yasir Alifriend11
Binary Association
• Associates objects of exactly two classes
• Denoted by a line, or an arrow between the associated objects
April 10, 2023 COMSATS Intitute of Information Technology 137
Example – Binary Association
• Association “works-for” associates objects of exactly two classes
April 10, 2023 COMSATS Intitute of Information Technology 138
Employee Companyworks-for1*
Example – Binary Association
• Association “drives” associates objects of exactly two classes
April 10, 2023 COMSATS Intitute of Information Technology 139
Ali Cardrives*1
Ternary Association
• Associates objects of exactly three classes
• Denoted by a diamond with lines connected to associated objects
April 10, 2023 COMSATS Intitute of Information Technology 140
Example – Ternary Association
• Objects of exactly three classes are associated
April 10, 2023 COMSATS Intitute of Information Technology 141
Student Teacher
Course
1
*
*
Example – Ternary Association
• Objects of exactly three classes are associated
April 10, 2023 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
April 10, 2023 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).
April 10, 2023 COMSATS Intitute of Information Technology
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
April 10, 2023 COMSATS Intitute of Information Technology 145
146
Class diagram showing composition
April 10, 2023 COMSATS Intitute of Information Technology
Composition among classes is shown as solid diamond arrowhead in UML Class Diagram.
Example – Composition of Ali
April 10, 2023 COMSATS Intitute of Information Technology 147
Ali
Body
Arm
Head
Leg
1
1
2 2
Example – Composition of Chair
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 150
Example – Composition is Stronger
• Chair’s body is made up of different parts
• They can’t exist independently
April 10, 2023 COMSATS Intitute of Information Technology 151
10 April 2023 National University of Computer and Emerging Sciences
152
Composition
• Composition is a ‘consists of’ relationship.• COURSE_DATA consists of STUDENT_DATA (besides other things).• STUDENT_DATA lifetime is the same as COURSE_DATA.
• Part may belong to only one whole.• The lifetime of the part is the same as the lifetime of the whole.
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
April 10, 2023 COMSATS Intitute of Information Technology 154
155
Class diagram showing aggregation
April 10, 2023 COMSATS Intitute of Information Technology
Aggregation among classes is shown as open diamond arrowhead in UML Class Diagram.
Example – Aggregation
April 10, 2023 COMSATS Intitute of Information Technology 156
Room
Cupboard
Bed
Chair Table*
1
1
1
Aggregation is Weaker
• Aggregation is weaker relationship, because• Aggregate object is not a part of the container• Aggregate object can exist independently
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 160
10 April 2023 National University of Computer and Emerging Sciences
161
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.
10 April 2023 National University of Computer and Emerging Sciences
162
More about ‘struct’ … struct TEST{
int x;}
TEST var;var.x = 10;
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++; }
April 10, 2023 COMSATS Intitute of Information Technology 163
10 April 2023 National University of Computer and Emerging Sciences
164
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();
struct TEST{private:
int x;}
TEST var;var.x = 10; //eint y = var.x; //e
So even legitimate access of data goes through an interface! We have secured the data further!!!
10 April 2023 National University of Computer and Emerging Sciences
165
Member functions definitionstruct 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
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 167
Example – Class Compatibility
April 10, 2023 COMSATS Intitute of Information Technology 168
ShapecolorverticesmovesetColordraw
CircleradiusdrawcomputeArea
Linelength
drawgetLength
Triangleangle
drawcomputeArea
Example – Class Compatibility
April 10, 2023 COMSATS Intitute of Information Technology 169
Filesize…openprint…
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
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 171
Example – Polymorphism
April 10, 2023 COMSATS Intitute of Information Technology 172
Shape
Line Circle Triangledraw
draw
draw draw
drawView
Example – Polymorphism
April 10, 2023 COMSATS Intitute of Information Technology 173
File
ASCII File PDF File PS Fileprint
print print
printEditor
Polymorphism – Advantages• Messages can be interpreted in different ways
depending upon the receiver class
April 10, 2023 COMSATS Intitute of Information Technology 174
Shape
Line Circle Triangledraw
draw
draw draw
drawView
Polymorphism – Advantages• New classes can be added without changing the existing
model
April 10, 2023 COMSATS Intitute of Information Technology 175
Squaredraw
Shape
Line Circle Triangledraw
draw
draw draw
drawView
Polymorphism – Advantages
• In general, polymorphism is a powerful tool to develop flexible and reusable systems
April 10, 2023 COMSATS Intitute of Information Technology 176
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.
April 10, 2023 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.
April 10, 2023 COMSATS Intitute of Information Technology 179
…Identify Classes
Eliminate irrelevant classes
• Editor – Very broad scope
• User – Out of system boundary
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 181
…Identify Classes
• Shape• Line• Circle• Triangle• Menu
April 10, 2023 COMSATS Intitute of Information Technology 182
• Group• View
Following classes have been identified:
Object Model – Graphic Editor
April 10, 2023 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)
April 10, 2023 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)
April 10, 2023 COMSATS Intitute of Information Technology 185
… Identify Associations
Verify access paths
• Menu sends message to View(Simple One-Way Association)
April 10, 2023 COMSATS Intitute of Information Technology 186
Object Model – Graphic Editor
April 10, 2023 COMSATS Intitute of Information Technology 187
TriangleCircleLine
ShapeView
nnnnnn
nnMenu
Groupnn
nnnn
nn
nn
Identify Attributes
Extract properties of the object• From the problem statement
• Properties are not mentioned
April 10, 2023 COMSATS Intitute of Information Technology 188
…Identify Attributes
Extract properties of the object• From the domain knowledge
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 190
• Group– noOfObjects
• View– noOfObjects– selected
• Menu– Name– isOpen
Object Model – Graphic Editor
April 10, 2023 COMSATS Intitute of Information Technology 191
MenunameisOpen
ViewnoOfObjectsselected
Shapecolorvertices
Linelength
Circleradius
GroupnoOfObjects
Triangleangle
nn
n
nn
n
nn
n
n
nn
nn
nn
n
Identify Operations
Extract verbs connected with an object
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 193
…Identify Operations
Following are selected operations:
April 10, 2023 COMSATS Intitute of Information Technology 194
• Line– Draw– Select– Move– Rotate
• Circle– Draw– Select– Move– Rotate
…Identify Operations
Following are selected operations:
April 10, 2023 COMSATS Intitute of Information Technology 195
• Triangle– Draw– Select– Move– Rotate
• Shape– Draw– Select– Move– Rotate
…Identify Operations
Following are selected operations:
April 10, 2023 COMSATS Intitute of Information Technology 196
• Group– Draw– Select– Move– Rotate
• Menu– Open– Select– Move– Rotate
…Identify Operations
Extract operations using domain knowledge
April 10, 2023 COMSATS Intitute of Information Technology 197
• View– Add– Remove– Group– Show
– Select– Move– Rotate
GroupnoOfObjects
draw()
Triangleangle
draw()nn
Circleradius
draw()nn
Linelength
draw()
nn
Shapecolorvertices
draw()select()move()rotate()
nn
ViewnoOfObjectsselected
add()remove()group()show()select()move()rotate()
nn
nnnn
nn
MenunameisOpen
open()select()move()rotate()
n
April 10, 2023 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
April 10, 2023 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
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 202
…Refining the Object Model
Share attributes
• Shape – Line, Circle, Triangle and Group• Color, vertices
April 10, 2023 COMSATS Intitute of Information Technology 203
…Refining the Object Model
Share operations
• Shape – Line, Circle, Triangle and Group• Select• Move• Rotate
April 10, 2023 COMSATS Intitute of Information Technology 204
…Refining the Object Model
Share the interface and override implementation
• Shape – Line, Circle, Triangle and Group• Draw
April 10, 2023 COMSATS Intitute of Information Technology 205
Linelength
draw()
Circleradius
draw()
Triangleangle
draw()
GroupnoOfObjects
draw()
Shapecolorvertices
draw()select()move()rotate()
n
ViewnoOfObjectsselected
add()remove()group()show()select()move()rotate()
nn
MenunameisOpen
open()select()move()rotate()
n
April 10, 2023 COMSATS Intitute of Information Technology 206
GroupnoOfObjects
draw()
Triangleangle
draw()nn
Circleradius
draw()nn
Linelength
draw()
nn
Shapecolorvertices
draw()select()move()rotate()
nn
ViewnoOfObjectsselected
add()remove()group()show()select()move()rotate()
nn
nnnn
nn
MenunameisOpen
open()select()move()rotate()
n
April 10, 2023 COMSATS Intitute of Information Technology 207
Class
• Class is a tool to realize objects• Class is a tool for defining a new type
April 10, 2023 COMSATS Intitute of Information Technology 208
Example
• Lion is an object• Student is an object• Both has some attributes and some behaviors
April 10, 2023 COMSATS Intitute of Information Technology 209
Uses
• The problem becomes easy to understand• Interactions can be easily modeled
April 10, 2023 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
April 10, 2023 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
April 10, 2023 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();
…
};
April 10, 2023 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);
…};April 10, 2023 COMSATS Intitute of Information Technology 214
Member variablesM
emb
er Fu
nction
s
Why Member Function
• They model the behaviors of an object• Objects can make their data invisible• Object remains in consistent state
April 10, 2023 COMSATS Intitute of Information Technology 215
Example
Student aStudent;
aStudent.rollNo = 514;
aStudent.rollNo = -514; //Error
April 10, 2023 COMSATS Intitute of Information Technology 216
Object and Class
• Object is an instantiation of a user defined type or a class
April 10, 2023 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;
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 219
Exampleclass Student{
int rollNo;
void setRollNo(int aNo);
};
Student aStudent;
aStudent.rollNo;
April 10, 2023 COMSATS Intitute of Information Technology 220
Error
10 April 2023 National University of Computer and Emerging Sciences
221
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();
}
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!
10 April 2023 National University of Computer and Emerging Sciences
222
Diff. between struct & classclass TEST {
int x;
void Setx(int val) { x = val; };
int Getx() { return x; };
}
main() {TEST var;var.x = 10; //errorvar.Setx(10); //errorint y = var.Getx(); //error
}
struct TEST {int x;
void Setx(int val) { x = val; };
int Getx() { return x; };}main() {
TEST var;var.x = 10; //possiblevar.Setx(10);int y = var.Getx();
}
• By default struct (C++) members are public, whereas class members are private.
10 April 2023 National University of Computer and Emerging Sciences
223
Diff. between struct & classclass TEST {
int x;
public:
void Setx(int val) { x = val; };
int Getx() { return x; };
}
main() {TEST var;var.x = 10; //errorvar.Setx(10);int y = var.Getx();
}
struct TEST {private:
int x;public:
void Setx(int val) { x = val; };
int Getx() { return x; };}main() {
TEST var;var.x = 10; //errorvar.Setx(10);int y = var.Getx();
}• By default struct (C++) members are public, whereas class members are private.
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
April 10, 2023 COMSATS Intitute of Information Technology 225
Example
class Student{
private:
char * name;
int rollNo;
public:
void setName(char *);
void setRollNo(int);
...
};April 10, 2023 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);
}April 10, 2023 COMSATS Intitute of Information Technology 227
Default access specifiers
• When no access specifier is mentioned then by default the member is considered private member
April 10, 2023 COMSATS Intitute of Information Technology 228
Exampleclass Student
{
char * name;
int RollNo;
};
class Student
{
private:
char * name;
int RollNo;
};
April 10, 2023 COMSATS Intitute of Information Technology 229
Exampleclass Student{char * name;int RollNo;void SetName(char *);};Student aStudent;aStudent.SetName(Ali);
April 10, 2023 COMSATS Intitute of Information Technology 230
Error
Exampleclass Student{char * name;int RollNo;public:void setName(char *);};Student aStudent;aStudent.SetName(“Ali”);
April 10, 2023 COMSATS Intitute of Information Technology 231
10 April 2023 National University of Computer and Emerging Sciences
Unified Modeling Language (UML) class diagram
232 of 21
10..*
abstractstatic
private
association(“using”)
inheritance(“is a”)
233
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
April 10, 2023 COMSATS Intitute of Information Technology
234
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]
April 10, 2023 COMSATS Intitute of Information Technology
CSC241:Object Oriented ProgrammingSpring 2013
1. Inheritance Concepts2. Polymorphism
April 10, 2023 COMSATS Intitute of Information Technology
236
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan Aadil
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 definitionOR
• Define member function outside the class definition• But they must be declared inside class definition
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
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
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{
…
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 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
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
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);
}
Example
Student::Student( char * aName = NULL,
int aRollNo= 0,
float aGPA = 0.0){
…
}
Is equivalent toStudent();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(char * Name, int aRollNo, float aGPA);
266
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]
April 10, 2023 COMSATS Intitute of Information Technology
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
April 10, 2023 COMSATS Intitute of Information Technology 267
CSC241:Object Oriented ProgrammingSpring 2013
1. Functions
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan Aadil
Functions
April 10, 2023 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.
Functions
April 10, 2023 COMSATS Intitute of Information Technology 273
//demonstrates a simple function#include <iostream>using namespace std;int cube(int x); // function derationint main(){ // tests the cube() function: int n = 1;
while (n != 0){cin >> n;cout << "\tcube(" << n << ") = “
<< cube(n) << endl; // Calling a function} // end of while loopsystem("PAUSE"); return 0;
}//end of mainint cube( int x ){ // function definition
return x*x*x; // returns cube of x:} // { function body }
Input Arguments
Return type
Functions
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 275
#include <iostream>using namespace std;//declaration with default argumentsvoid 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 charactersvoid 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
April 10, 2023 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
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 279
#include <iostream>using namespace std;// calls itself to calculate factorialsunsigned long fct(unsigned long n){ static int I = 0; I++; cout << "You Called Me " << I << " times" << endl; if(n > 1) return n * fct(n-1); //self 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;}
281
References
• “Object Oriented Programming in C++”, by “Robert Lafore”, published by Sams Publishing (The Waite Group). 4th ed. available in soft form.
April 10, 2023 COMSATS Intitute of Information Technology
CSC241:Object Oriented ProgrammingSpring 2013
1. Constructors
April 10, 2023 COMSATS Intitute of Information Technology
283
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan Aadil
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
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
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);
}
Example
Student::Student( char * aName = NULL,
int aRollNo= 0,
float aGPA = 0.0){
…
}
Is equivalent toStudent();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(char * Name, int aRollNo, float aGPA);
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
GPARollNo
studentA
Name
GPARollNo
studentBAHMAD…
Memory
304
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]
April 10, 2023 COMSATS Intitute of Information Technology
CSC241:Object Oriented ProgrammingSpring 2013
1. Destructor
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan Aadil
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.
April 10, 2023 COMSATS Intitute of Information Technology 308
Using Destructor
April 10, 2023 COMSATS Intitute of Information Technology 309
// foo.cpp demonstrates destructor#include <iostream>using namespace std;class Foo{ private:
int data; public:
Foo() : data(0) // constructor (same name as class)
{cout<< "Wakeup \n" ; }~Foo() // destructor (same name with tilde)
{cout<< "ByeBye \n" ; }};int main(){
Foo s1, s2; // define two objects of class Foosystem( "PAUSE" ); // Foo *s3; s3 = new Foo; delete s3;return 0;
}
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
Exampleclass Complex{ //old
float x;
float y;
public:
void setNumber(float i, float j){
x = i;
y = j;
}
…
};
Exampleclass 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.cpp
#include “student.h”
void Student::setRollNo(int aNo){
…
}
int Student::getRollNo(){
…
}
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.
April 10, 2023 COMSATS Intitute of Information Technology 323
325
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]
April 10, 2023 COMSATS Intitute of Information Technology
CSC241:Object Oriented ProgrammingSpring 2013
1. Static class member2. Const member function
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan Aadil
10 April 2023 COMSATS Intitute of Information Technology 328
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?
10 April 2023 COMSATS Intitute of Information Technology 329
static class member dataclass foo {
private:
static int count; //note: “declaration” only!
public:
foo() //incr count when object created
{ count++;
}
int getcount() //returns count
{ return count;
}
};
int foo::count = 0; //*definition* of count
int main(){foo f1, f2, f3; //create three objectscout << “count is “ << f1.getcount()
<< endl; //each objectcout << “count is “ << f2.getcount()
<< endl; //sees thecout << “count is “ << f3.getcount()
<< endl; //same valuereturn 0;}
10 April 2023 COMSATS Intitute of Information Technology 330
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)
10 April 2023 COMSATS Intitute of Information Technology 331
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.
10 April 2023 COMSATS Intitute of Information Technology 332
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).
10 April 2023 COMSATS Intitute of Information Technology 333
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.
10 April 2023 COMSATS Intitute of Information Technology 334
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)
{
}
}
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
April 10, 2023 COMSATS Intitute of Information Technology 335
Example
bool Student::isRollNo(int aNo){
if(rollNo = = aNo){
return true;
}
return false;
}
April 10, 2023 COMSATS Intitute of Information Technology 336
Example
bool Student::isRollNo(int aNo){
/*undetected typing mistake*/
if(rollNo = aNo){
return true;
}
return false;
}
April 10, 2023 COMSATS Intitute of Information Technology 337
Example
bool Student::isRollNo
(int aNo)const{
/*compiler error*/
if(rollNo = aNo){
return true;
}
return false;
}
April 10, 2023 COMSATS Intitute of Information Technology 338
const Member Functions
•Keyword const is placed at the end of the parameter list
April 10, 2023 COMSATS Intitute of Information Technology 339
const Member Functions
Declaration:class ClassName{
ReturnVal Function() const;
};
Definition:ReturnVal ClassName::Function() const{
…
}
April 10, 2023 COMSATS Intitute of Information Technology 340
Example
class Student{
public:
int getRollNo() const {
return rollNo;
}
};
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 343
Example
class Time{public:Time() const {} //error…~Time() const {} //error…};
April 10, 2023 COMSATS Intitute of Information Technology 344
const Function
•Constant member function cannot change data member
•Constant member function cannot access non-constant member functions
April 10, 2023 COMSATS Intitute of Information Technology 345
Example
class Student{char * name;
public:char *getName();void setName(char * aName);int ConstFunc() const{
name = getName();//errorsetName(“Ahmad”);//error
}};
April 10, 2023 COMSATS Intitute of Information Technology 346
348
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]
April 10, 2023 COMSATS Intitute of Information Technology
CSC241:Object Oriented ProgrammingSpring 2013
1. Arrays & String (Chapter 7)
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan 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); // declarationint main(){ int a[] = { 11,33, 55,77 }; int size = sizeof(a)/sizeof(int); cout << "sum(a,size) = " << sum(a,size) << endl; cout << endl << a[0] << endl; system("PAUSE"); return 0;}int sum(int a[],int n){ int sum=0; for (int i=0; i<n; i++) sum += a[i]; a[0] = 100; return sum;}
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 Arrays0x22ff30 = 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 Algovoid sort( float a[], int n ){ // bubble sort: for (int i=1; i<n; i++) // bubble up max{a[0..n-i]}: for (int j=0; j<n-i; j++) if (a[j] > a[j+1]){ float temp = a[j]; a[j]=a[j+1]; a[j+1] = temp; }}
void print( float a[], int n ){cout << " Sorted Data is " << endl;for (int i=0; i<n; i++)
cout << a[i] <<" ";}
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 stringchar str[MAX]; // string variable strcout << "\nEnter a string: ";// cin.get() means a member function get() of the stream// class of which cin is an objectcin.get(str, MAX); // put string in str// first argument to get() is the array address where the// string being input will be placed.// The second argument specifies the maximum size of the// arraycout << "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 bufferchar str2[MAX]; //empty stringfor( j=0; j<strlen(str1); j++) //copy strlen characters
str2[j] = str1[j]; // from str1 to str2str2[j] = '\0'; //insert NULL at endcout << str2 << endl; //display str2system("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 bright\n"
"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 arrayconst int MAX = 10; //maximum size of each string//An array of stringschar star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday" , "Saturday" };for( int j=0 ; j<DAYS ; j++) //display every string
cout << star[j] << endl;system("PAUSE");return 0;
}
376
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]
April 10, 2023 COMSATS Intitute of Information Technology
CSC241:Object Oriented ProgrammingSpring 2013
1. Composition2. Aggregation3. Friend Functions
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan 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 (Aggregation)
int main(){
Student obj;
Student *ptr;
ptr = &obj;
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
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
}
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
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;
}
…
}
AggregationComposition vs. Aggregation
►Aggregation is a weak relationship
Room(char *, int)~Room()FoldChair(int) : bool…
Chair()DoSomething() : voidFoldChair() : boolUnFoldChair() : bool~Chair()…
area : floatchairs[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 NOT dependant on the life of its master class
►e.g:Chairs can be moved inside or outside at anytimeWhen Room is destroyed, the chairs may or may not be destroyed
Aggregationclass Room{private:
float area;Chair * chairs[50];
Public:Room();void AddChair(Chair *, int chairNo);Chair * GetChair(int chairNo);bool FoldChair(int chairNo);…
};
AggregationRoom::Room(){
for(int i = 0; i < 50; i++)
chairs[i] = NULL;}void Room::AddChair(Chair *
chair1, int chairNo){if(chairNo >= 0 && chairNo <
50)chairs[chairNo] = chair1;
}
AggregationChair * Room::GetChair(int chairNo){
if(chairNo >= 0 && chairNo < 50)return chairs[chairNo];
elsereturn NULL;
}
bool Room::FoldChair(int chairNo){ if(chairNo >= 0 && chairNo < 50)
return chairs[chairNo]->FoldChair(); 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
►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
420
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]
April 10, 2023 COMSATS Intitute of Information Technology
CSC241:Object Oriented ProgrammingSpring 2013
1. Operator Overloading
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
422
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan 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 &);…
}
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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;
}
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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)
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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)))
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
426
Operator overloading►Alternative way is:► t1 = c3.Add(c4);► t2 = c2.Add(t1);► t3 = c1.Add(t2);
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
430
Operator overloading ►C++ automatically overloads operators for
pre-defined types►Example of predefined types:
int
float
double
char
long
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
431
Operator overloading ►Example:
float x;
int y;
x = 102.02 + 0.09;
Y = 50 + 47;
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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)
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
433
Operator overloading
►Operator functions are not usually called directly
►They are automatically invoked to evaluate the operations they implement
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
434
Operator overloading►List of operators that can be
overloaded in C++: April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
437
Operator overloading
►Associativity is NOT changed due to overloading
►Following arithmetic expression always is evaluated
from left to right:c1 + c2 + c3 + c4
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
439
Operator overloading►Always write code representing
the operator►Example:
Adding subtraction code inside the + operator will create chaos
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
440
Operator overloading
►Creating a new operator is a syntax error (whether unary, binary
or ternary)► You cannot create $
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
442
Binary operators►Binary operators act on two quantities
►Binary operators:
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
443
Binary operators►General syntax:
Member function:
TYPE1 CLASS::operator B_OP(
TYPE2 rhs){
...
}
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
444
Binary operators►General syntax:
Non-member function:
TYPE1 operator B_OP(TYPE2 lhs, TYPE3
rhs){
...
}
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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);
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
446
Binary operators►Overloading + operator:
class Complex{
private:
double real, img;
public:
…
Complex operator +(const Complex & rhs);
};
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
447
Binary operators
Complex Complex::operator +(const Complex & rhs){
Complex t;
t.real = real + rhs.real;
t.img = img + rhs.img;
return t;
}
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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);
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
449
Binary operators
►If the return type was void, class Complex{
...► public:
► void operator+(► const Complex & rhs);
};
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
450
Binary operators
void Complex::operator+(const Complex & rhs){
real = real + rhs.real;
img = img + rhs.img;
};
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
451
Binary operators
►we have to do the same operation c1+c2+c3 as:c1+c2
c1+c3
// final result is stored in c1
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
452
Binary operators
►Drawback of void return type:Assignments and cascaded expressions are not possibleCode is less readableDebugging is toughCode is very hard to maintain
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
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]
April 10, 2023 COMSATS Intitute of Information Technology 454
CSC241:Object Oriented ProgrammingSpring 2013
1. Inheritance
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan 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
April 10, 2023 COMSATS Intitute of Information Technology 457
UML Notation
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 459
“IS A” Relationship
• IS A relationship is modeled with the help of public inheritance
• Syntaxclass ChildClass
: public BaseClass{
...
};
April 10, 2023 COMSATS Intitute of Information Technology 460
Exampleclass Person{
...
};
class Student: public Person{
...
};
April 10, 2023 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)
April 10, 2023 COMSATS Intitute of Information Technology 462
Exampleclass Person{
char *name;
int age;
...
public:
const char *GetName() const;
int GetAge() const;
...
};
April 10, 2023 COMSATS Intitute of Information Technology 463
Exampleclass Student: public Person{int semester;int rollNo;...
public:int GetSemester() const;int GetRollNo() const;void Print() const;...
};
April 10, 2023 COMSATS Intitute of Information Technology 464
Example
void Student::Print()
{
cout << name << “ is in” << “ semester ” << semester;
}
April 10, 2023 COMSATS Intitute of Information Technology 465
ERROR
Example
void Student::Print()
{
cout << GetName()
<< “ is in semester ” << semester;
}
April 10, 2023 COMSATS Intitute of Information Technology 466
Exampleint main(){
Student stdt;
stdt.semester = 0;//error
stdt.name = NULL; //error
cout << stdt.GetSemester();
cout << stdt.GetName();
return 0;
}
April 10, 2023 COMSATS Intitute of Information Technology 467
Allocation in Memory• The object of derived class is represented in memory
as follows
April 10, 2023 COMSATS Intitute of Information Technology 468
Data members of base class
Data members of derived class
base member1base member2
...
derived member1derived member2
...
Allocation in Memory• Every object of derived class has an anonymous
object of base class
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 470
Constructors
April 10, 2023 COMSATS Intitute of Information Technology 471
Base class constructor initializes the anonymous object
Derived class constructor initializes the derived class object
base member1base member2
...
derived member1derived member2
...
Exampleclass Parent{public:Parent(){ cout <<
“Parent Constructor...”;}};class Child : public Parent{public:Child(){ cout <<
“Child Constructor...”;}};
April 10, 2023 COMSATS Intitute of Information Technology 472
Exampleint main(){
Child cobj;
return 0;
}
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 475
Exampleclass Parent{
public:
Parent(int i){}
};
class Child : public Parent{
public:
Child(){}
} Child_Object; //ERROR
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 477
Exampleclass Parent{
public:
Parent(int i){…};
};
class Child : public Parent{
public:
Child(int i): Parent(i)
{…}
};
April 10, 2023 COMSATS Intitute of Information Technology 478
Exampleclass Parent{
public:
Parent(){cout <<
“Parent Constructor...”;}
...
};
class Child : public Parent{
public:
Child():Parent()
{cout << “Child Constructor...”;}
...
};
April 10, 2023 COMSATS Intitute of Information Technology 479
Base Class Initializer• User can provide base class initializer and
member initializer simultaneously
April 10, 2023 COMSATS Intitute of Information Technology 480
Exampleclass Parent{public:Parent(){…}
};class Child : public Parent{int member;
public:Child():member(0), Parent() {…}
};
April 10, 2023 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.
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 483
Exampleclass Person{public:int age;char *name;...
public:Person();
};
April 10, 2023 COMSATS Intitute of Information Technology 484
Exampleclass Student: public Person{
private:
int semester;
...
public:
Student(int a):age(a)
{ //error
}
};
April 10, 2023 COMSATS Intitute of Information Technology 485
Reason
• It will be an assignment not an initialization
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 487
Exampleclass Parent{
public:
Parent(){cout <<“Parent Constructor”;}
~Parent(){cout<<“Parent Destructor”;}
};
class Child : public Parent{
public:
Child(){cout << “Child Constructor”;}
~Child(){cout << “Child Destructo”;}
};
April 10, 2023 COMSATS Intitute of Information Technology 488
ExampleOutput:
Parent Constructor
Child Constructor
Child Destructor
Parent Destructor
April 10, 2023 COMSATS Intitute of Information Technology 489
Date Classclass Date{
int day, month, year;static Date defaultDate;
public:void SetDay(int aDay);int GetDay() const;void AddDay(int x);… static void SetDefaultDate(
int aDay,int aMonth, int aYear);
Date Class
...private:
bool IsLeapYear();};
int main(){Date aDate;aDate.IsLeapYear(); //Errorreturn 0;
}
Creating SpecialDate Class
class SpecialDate: public Date{…
public:void AddSpecialYear(int i){
...if(day == 29 && month == 2&& !IsLeapyear(year+i)){ //ERROR!
...}
}};
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(); //Errorreturn 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]
April 10, 2023 COMSATS Intitute of Information Technology 502
CSC241:Object Oriented ProgrammingSpring 2013
1. Inheritance
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan Aadil
Hierarchy of Inheritance• We represent the classes involved in inheritance
relation in tree like hierarchy
April 10, 2023 COMSATS Intitute of Information Technology 505
Example
April 10, 2023 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...
April 10, 2023 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{};
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 509
Example
class GrandParent{int gpData;
public: GrandParent() : gpData(0){...}GrandParent(int i) : gpData(i){...} void Print() const;
};
April 10, 2023 COMSATS Intitute of Information Technology 510
Example
class Parent1: public GrandParent{int pData;
public:Parent1() : GrandParent(), pData(0) {…}
};
April 10, 2023 COMSATS Intitute of Information Technology 511
Example
class Child1 : public Parent1 {public:
Child1() : Parent1() {...}Child1(int i) : GrandParent (i) //Error{...}void Print() const;
};
April 10, 2023 COMSATS Intitute of Information Technology 512
Overriding
• Child class can override the function of GrandParent class
April 10, 2023 COMSATS Intitute of Information Technology 513
Example
April 10, 2023 COMSATS Intitute of Information Technology 514
GrandParentPrint()
Parent1
Child1Print()
Example
void GrandParent::Print() { cout << “GrandParent::Print”
<< endl;}
void Child1::Print() { cout << “Child1::Print” << endl;
}April 10, 2023 COMSATS Intitute of Information Technology 515
Example
int main(){Child1 obj;obj.Print();obj.Parent1::Print();obj.GrandParent::Print();return 0;
}
April 10, 2023 COMSATS Intitute of Information Technology 516
Output
• Output is as follows
Child1::PrintGrandParent::PrintGrandParent::Print
April 10, 2023 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
April 10, 2023 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 {…}
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 523
Example
class Collection {...public:
void AddElement(int);bool SearchElement(int);bool SearchElementAgain(int);bool DeleteElement(int);
};April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology 525
Class Set
class Set: private Collection {private:
...public:
void AddMember(int);bool IsMember(int);bool DeleteMember(int);
};April 10, 2023 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);}
April 10, 2023 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]
April 10, 2023 COMSATS Intitute of Information Technology 528
CSC241:Object Oriented ProgrammingSpring 2013
1. Private Inheritance2. Specialization
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan 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 {…}
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology
Example
class Collection {...public:
void AddElement(int);bool SearchElement(int);bool SearchElementAgain(int);bool DeleteElement(int);
};April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology
Class Set
class Set: private Collection {private:
...public:
void AddMember(int);bool IsMember(int);bool DeleteMember(int);
};April 10, 2023 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);}
April 10, 2023 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
April 10, 2023 COMSATS Intitute of Information Technology
Specialization (Restriction)
• Specialization (Restriction) can be implemented using private and protected inheritance
April 10, 2023 COMSATS Intitute of Information Technology
Example – Specialization (Restriction)
April
10,
202
3CO
MSA
TS In
titut
e of
Info
rmati
on
Tech
nolo
gy
Personage : [0..125]
Adultage : [18..125]
setAge( a )
setAge( a )
age = a
If age < 18 then errorelse 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;
}};
April 10, 2023 COMSATS Intitute of Information Technology
Exampleclass Adult : private Person {
public:bool SetAge(int _age){
if (_age >=18 && _age <= 125) {age = _age;return true;
}return false;
}};April 10, 2023 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
April 10, 2023 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().
April 10, 2023 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.
April 10, 2023 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.
April 10, 2023 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]
April 10, 2023 COMSATS Intitute of Information Technology
CSC241:Object Oriented ProgrammingSpring 2013
1. Overriding & Overloading2. Multiple Inheritance3. Virtual Inheritance4. Virtual Functions/Members
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan 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
April 10, 2023 COMSATS Institute of Information Technology 553
Overriding
April 10, 2023 COMSATS Institute of Information Technology 554
Parent...
Func1
Child...
Func1
Overriding
class Parent {public:
void Func1();void Func1(int);
};
class Child: public Parent {public:
void Func1();};April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 556
Overriding
class Parent {public:
void Func1();void Func1(); //Error
};
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 558
Example
class Person{public:
void Walk();};class ParalyzedPerson: public Person{public:
void Walk();};April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 560
Exampleclass Person{char *name;public:Person(char *=NULL);const char *GetName() const;void Print(){
cout << “Name: ” << name << endl;
}};April 10, 2023 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;}
...};
April 10, 2023 COMSATS Institute of Information Technology 562
Example
int main(){
Student a(“Ahmad”, “Computer Science”);
a.Print();
return 0;
}
April 10, 2023 COMSATS Institute of Information Technology 563
Output
Output:
Name: AhmedMajor: Computer Science
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 565
Exampleclass Student : public Person{char * major;
public:Student(char * aName, char* m);
void Print(){Print();//Print of Personcout<<“Major:” << major <<endl;
}...};
April 10, 2023 COMSATS Institute of Information Technology 566
Example
int main(){
Student a(“Ahmad”, “Computer Science”);
a.Print();
return 0;
}
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 568
Exampleclass Student : public Person{char * major;
public:Student(char * aName, char* m);
void Print(){Person::Print();cout<<“Major:” << major <<endl;
}...};
April 10, 2023 COMSATS Institute of Information Technology 569
Example
int main(){
Student a(“Ahmad”, “Computer Science”);
a.Print();
return 0;
}
April 10, 2023 COMSATS Institute of Information Technology 570
Output
Output:
Name: AhmedMajor: Computer Science
April 10, 2023 COMSATS Institute of Information Technology 571
{Before New Topic……}• I need Your anonymous Feed Back
• About the Instructor•&• About the CourseApril 10, 2023 COMSATS Institute of Information Technology 572
Multiple Inheritance
• A class can inherit from more then one class
April 10, 2023 COMSATS Institute of Information Technology 573
Multiple Inheritance
April 10, 2023 COMSATS Institute of Information Technology 574
Transmitter...
Transmit()
Receiver...
Receive()
Phone
Example
class Phone: public Transmitter, public Receiver
{...};
April 10, 2023 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
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 577
Example
int main(){Phone obj;obj.Transmit();obj.Receive();return 0;
}
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 579
Example
int main(){Phone obj;Transmitter * tPtr = &obj;Receiver * rPtr = &obj;return 0;
}
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 581
Example
int main(){Phone obj;Transmitter * tPtr = &obj;tPtr->Transmit(); tPtr->Receive(); //Errorreturn 0;
}
April 10, 2023 COMSATS Institute of Information Technology 582
Example
int main(){Phone obj;Receiver * rPtr = &obj;rPtr->Receive(); rPtr->Transmit(); //Errorreturn 0;
}
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 584
Multiple Inheritance
April 10, 2023 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();};April 10, 2023 COMSATS Institute of Information Technology 586
Example
class AmphibiousVehicle: public LandVehicle, public WaterVehicle{
};int main(){
AmphibiousVehicle obj;obj.GetMaxLoad(); // Errorreturn 0;
}April 10, 2023 COMSATS Institute of Information Technology 587
Multiple Inheritance
• Programmer must explicitly specify the class name when calling ambiguous function
April 10, 2023 COMSATS Institute of Information Technology 588
Example
int main(){AmphibiousVehicle obj; obj.LandVehicle::GetMaxLoad();obj.WaterVehicle::GetMaxLoad();return 0;
}
April 10, 2023 COMSATS Institute of Information Technology 589
Multiple Inheritance
• The ambiguous call problem can arise when dealing with multiple level of multiple inheritance
April 10, 2023 COMSATS Institute of Information Technology 590
Multiple Inheritance
April 10, 2023 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{};April 10, 2023 COMSATS Institute of Information Technology 592
Example
class AmphibiousVehicle: public LandVehicle, public WaterVehicle{
};int main(){
AmphibiousVehicle obj;obj.GetMaxLoad(); // Errorreturn 0;
}April 10, 2023 COMSATS Institute of Information Technology 593
Example
int main(){
AmphibiousVehicle obj; obj.Vehicle::GetMaxLoad(); //Errorreturn 0;
}• Vehicle is accessible through two pathsApril 10, 2023 COMSATS Institute of Information Technology 594
Multiple Inheritance
April 10, 2023 COMSATS Institute of Information Technology 595
Amphibious Vehicle
Land Vehicle Water Vehicle
Vehicle
Car Boat
Vehicle
Exampleint main(){
AmphibiousVehicle obj; obj.LandVehicle::GetMaxLoad();obj.WaterVehicle::GetMaxLoad();return 0;
}
April 10, 2023 COMSATS Institute of Information Technology 596
Multiple Inheritance
• Data member must be used with care when dealing with more then one level on inheritance
April 10, 2023 COMSATS Institute of Information Technology 597
Example
class Vehicle{protected:
int weight;};class LandVehicle : public Vehicle{};class WaterVehicle : public Vehicle{};April 10, 2023 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 weightApril 10, 2023 COMSATS Institute of Information Technology 599
Memory View
April
10,
202
3CO
MSA
TS In
stitu
te o
f Inf
orm
ation
Te
chno
logy
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
April 10, 2023 COMSATS Institute of Information Technology 601
Example
class Vehicle{protected:
int weight;};class LandVehicle :
public virtual Vehicle{};class WaterVehicle :
public virtual Vehicle{};April 10, 2023 COMSATS Institute of Information Technology 602
Example
class AmphibiousVehicle: public LandVehicle, public WaterVehicle{
public: AmphibiousVehicle(){ weight = 10;}
};April 10, 2023 COMSATS Institute of Information Technology 603
Memory View
April 10, 2023 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
April 10, 2023 COMSATS Institute of Information Technology 605
Example
April 10, 2023 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]
April 10, 2023 COMSATS Institute of Information Technology 607
CSC241:Object Oriented ProgrammingSpring 2013
1. Generic Programming2. Templates
Please turn OFF your Mobile Phones!
Monday, April 10, 2023Farhan Aadil
Quiz
• Explain “Diamond of Death” with help of Class Diagram, also write code for your class diagram.
April 10, 2023 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??
April 10, 2023 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…April 10, 2023 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
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
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 templateisEqual( 7.5, 7.5 );// Target: general template
isEqual( “abc”, “xyz” );// Target: user specializationreturn 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]
April 10, 2023 COMSATS Institute of Information Technology 637
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): "; cin >> title; cout << " Enter price: "; cin >> price; } void putdata() { cout << "\n Title: " << title; cout << "\n Price: " << price; } };////////////////////////////////////////////////////////////////class book : private publication { private: int pages; public: void getdata() { publication::getdata(); cout << " Enter number of pages: "; cin >> pages; } void putdata() { publication::putdata(); cout << "\n Pages: " << pages; } };////////////////////////////////////////////////////////////////class tape : private publication { private: float time; public: void getdata() { publication::getdata(); cout << " Enter playing time: "; cin >> time; } void putdata() { publication::putdata(); cout << "\n Playing time: " << time; } };////////////////////////////////////////////////////////////////class disk : private publication { private: disktype type; public: void getdata(); void putdata() { publication::putdata(); cout << "\n Disk type: "; cout << (type==CD ? "CD" : "DVD"); } };//--------------------------------------------------------------void disk::getdata() { char ch; publication::getdata(); // get title and price do { // loop until correct size cout << " Enter disk type (c for CD, d for DVD): "; cin >> ch; switch(ch) { // set disk type case 'c': type = CD; break; case 'd': type = DVD; break; default: cout << "Incorrect type\n"; } } while(ch!='c' && ch!='d'); }////////////////////////////////////////////////////////////////int main() { book book1; // define publications tape tape1; disk disk1;
cout << "\nBook"; // get data for them book1.getdata(); cout << "\nTape"; tape1.getdata(); cout << "\nDisk"; disk1.getdata();
cout << "\nBook"; // display their data book1.putdata(); cout << "\nTape"; tape1.putdata(); cout << "\nDisk"; disk1.putdata(); cout << endl; return 0; }