OOP Complete Notes
OOP Complete Notes
BY
Umer Tanvir
Spring 2013
1. Starting OOP
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
1/25/16
COMSATS Institute of Information Technology
CSC241:
Object Oriented
Programming
Study Assignment
I hope you did go through chapter 1 of both the books.
How was the experience?
What did you learn?
1/25/16
Object Oriented
Object-Orientation
(OO)
1/25/16
What is Object-Orientation?
A technique for system modeling
OO model consists of several interacting objects
1/25/16
What is a Model?
A model is an abstraction of something
Purpose is to understand the product before developing
it
1/25/16
Examples Model
Highway maps
Architectural models
Mechanical models
1/25/16
Example OO Model
1/25/16
Example OO Model
Ali
Objects
Ali
House
Car
Tree
lives-in
House
drives
Car
Tree
Interactions
Ali lives in the house
Ali drives the car
1/25/16
10
Object-Orientation - Advantages
People think in terms of objects
OO models map to reality
Therefore, OO models are
easy to develop
easy to understand
1/25/16
11
What is an Object?
An object is
Something tangible (Ali, Car)
Something that can be apprehended intellectually
(Time, Date)
1/25/16
12
What is an Object?
An object has
State (attributes)
Well-defined behaviour (operations)
Unique identity
1/25/16
13
behaviour (operations)
Walks
Eats
Identity
His name
1/25/16
14
behaviour (operations)
- Start Car
- Accelerate
- Change Gear
Identity
- Its registration number
1/25/16
15
- Seconds
behaviour (operations)
- Set Hours
- Set Minutes
- Set Seconds
Identity
- Would have a unique ID in the model
1/25/16
16
- Day
behaviour (operations)
- Set Year
- Set Day
- Set Month
Identity
- Would have a unique ID in the model
1/25/16
17
Definition
What Is an Object?
An object is a software bundle of related variables and
methods. Software objects are often used to model realworld 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.
1/25/16
18
1/25/16
19
1/25/16
20
1/25/16
21
22
23
1/25/16
24
25
26
27
Abstraction
Abstraction is a way to cope with complexity.
Principle of abstraction:
Capture only those details about an object that are
relevant to current perspective
1/25/16
28
Example Abstraction
Ali is a PhD student and teaches BS
students
Attributes
-
1/25/16
Name
Student Roll No
Year of Study
CGPA
- Employee ID
- Designation
- Salary
- Age
29
Example Abstraction
Ali is a PhD student and teaches BS
students
behaviour
-
1/25/16
Study
- DevelopExam
GiveExam
- TakeExam
PlaySports
- Eat
DeliverLecture
- Walk
30
Example Abstraction
Students Perspective
Attributes
1/25/16
Name
Student Roll No
Year of Study
CGPA
- Employee ID
- Designation
- Salary
- Age
31
Example Abstraction
Students Perspective
behaviour
-
1/25/16
Study
- DevelopExam
GiveExam
- TakeExam
PlaySports
- Eat
DeliverLecture
- Walk
32
Example Abstraction
Teachers Perspective
Attributes
-
1/25/16
Name
Student Roll No
Year of Study
CGPA
- Employee ID
- Designation
- Salary
- Age
33
Example Abstraction
Teachers Perspective
behaviour
-
1/25/16
Study
- DevelopExam
GiveExam
- TakeExam
PlaySports
- Eat
DeliverLecture
- Walk
34
Example Abstraction
A cat can be viewed with different
perspectives
Surgeons
Perspective
Ordinary
Perspective
A pet animal with
Four Legs
A Tail
Two Ears
Sharp Teeth
1/25/16
A being with
A Skeleton
Heart
Kidney
Stomach
35
Example Abstraction
Engineers View
Drivers View
1/25/16
36
Abstraction Advantages
Simplifies the model by hiding irrelevant details
Abstraction provides the freedom to defer
implementation decisions by avoiding commitment to
details
1/25/16
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
1/25/16
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
1/25/16
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
1/25/16
40
(Class Name)
Suppressed
Form
Normal
Form
1/25/16
41
Circle
Suppressed
Form
Normal
Form
1/25/16
42
Person
Suppressed
Form
Normal
Form
1/25/16
43
Inheritance
A child inherits characteristics of its parents
Besides inherited characteristics, a child may have its
own unique characteristics
1/25/16
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
1/25/16
45
Example Inheritance
Person
Student
1/25/16
Teacher
Doctor
46
Example Inheritance
Shape
Line
1/25/16
Circle
Triangle
47
Inheritance IS A or
IS A KIND OF Relationship
Each derived class is a special kind of its base class
1/25/16
48
Example IS A Relationship
Person
name
age
gender
eat
walk
Student
1/25/16
program
studyYear
study
heldExam
Teacher
designation
salary
teach
takeExam
Doctor
designation
salary
checkUp
prescribe
49
Example IS A Relationship
Shape
color
coord
draw
rotate
setColor
Circle
1/25/16
radius
Line
length
draw
computeAreaCOMSATS Institute
draw
of Information Technology
Triangle
angle
draw
computeArea
50
Inheritance Advantages
Reuse
Less redundancy
Increased maintainability
1/25/16
51
1/25/16
52
Example Reuse
Shape
color
coord
draw
rotate
setColor
Circle
1/25/16
radius
draw
computeArea
Triangle
angle
length
draw
computeArea
draw
COMSATS Institute of Information Technology
53
Line
Example Reuse
Person
name
age
gender
eat
walk
Student
1/25/16
program
studyYear
study
heldExam
Teacher
designation
salary
teach
takeExam
Doctor
designation
salary
checkUp
prescribe
54
Example Reuse
Person
name
age
gender
eat
walk
Student
1/25/16
program
studyYear
study
heldExam
Teacher
designation
salary
teach
takeExam
Doctor
designation
salary
checkUp
prescribe
55
1/25/16
References
56
Thanks
1/25/16
57
Spring 2013
1. Inheritance & Generalization
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
1/25/16
COMSATS Institute of Information Technology
CSC241:
Object Oriented
Programming
58
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
1/25/16
59
1/25/16
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
1/25/16
61
Example Generalization
Line
color
vertices
length
move
setColor
getLength
1/25/16
Circle
color
vertices
radius
move
setColor
computeArea
Triangle
color
vertices
angle
move
setColor
computeArea
62
Example Generalization
Shape
color
vertices
move
setColor
Circle
Triangle
radius
computeArea
1/25/16
Line
length
getLength
angle
computeArea
63
Example Generalization
Student
name
age
gender
program
studyYear
study
heldExam
eat
walk
1/25/16
Teacher
name
age
gender
designation
salary
teach
takeExam
eat
walk
COMSATS Institute of Information Technology
Doctor
name
age
gender
designation
salary
checkUp
prescribe
eat
walk
64
Example Generalization
Person
name
age
gender
eat
walk
Student
1/25/16
program
studyYear
study
heldExam
Teacher
designation
salary
teach
takeExam
Doctor
designation
salary
checkUp
prescribe
65
1/25/16
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
1/25/16
67
Person
name
age
gender
eats
walks
Example
Sub-typing
(Extension)
1/25/16
Student
program
studyYear
study
takeExam
68
Shape
color
vertices
setColor
move
Example
Sub-typing
(Extension)
Circle
radius
computeCF
computeArea
1/25/16
69
Specialization (Restriction)
Specialization means that derived class is behaviourally
incompatible with the base class
Behaviourally incompatible means that base class cant
always be replaced by the derived class
1/25/16
70
setAge( a )
Adult
1/25/16
age : [18..100]
setAge( a )
age = a
71
add( elem )
NaturalSet
add( elem )
1/25/16
add
element to
the set
If elem < 1
then
error
else
add
element to
the set
72
Overriding
A class may need to override the default behaviour
provided by its base class
Reasons for overriding
1/25/16
73
color
vertices
draw
move
setColor
Circle
1/25/16
radius
Line
length
draw
computeAreaCOMSATS Institute
draw
of Information Technology
Triangle
angle
draw
computeArea
74
Example Extension
Window
width
height
open
close
draw
DialogBox
controls
enable
draw
1/25/16
1- Invoke
Windows
draw
2- draw the
dialog box
COMSATS Institute of Information Technology
75
Example Restriction
IntegerSet
add( elem )
NaturalSet
add( elem )
1/25/16
Add element
to the set
If elem < 1
then
give error
else
Add element
to the set
76
color
coord
draw
rotate
setColor
Circle
radius
draw
rotate
1/25/16
77
Abstract Classes
An abstract class implements an abstract concept
Main purpose is to be inherited by other classes
Cant be instantiated
Promotes reuse
1/25/16
78
Student
1/25/16
Teacher
Doctor
Here, Person
is an abstract class
COMSATS Institute of Information Technology
79
Car
1/25/16
Bus
Truck
Here, Vehicle
is an abstract class
COMSATS Institute of Information Technology
80
Concrete Classes
A concrete class implements a concrete concept
Main purpose is to be instantiated
Provides implementation details specific to the domain
context
1/25/16
81
1/25/16
Teacher
Doctor
1/25/16
Bus
Truck
capacity
load
unload
83
Multiple Inheritance
We may want to reuse characteristics of more than one
parent class
1/25/16
84
1/25/16
Mermai
85
Woman
Fish
Mermaid
1/25/16
86
Amphibious
Vehicle
1/25/16
87
Car
1/25/16
Water Vehicle
Amphibious Vehicle
COMSATS Institute of Information Technology
Boat
88
1/25/16
89
eat
eat
Fish
Mermaid
Which eat operation Mermaid inherits?
1/25/16
90
eat
eat
Mermaid
eat
1/25/16
Fish
Invoke eat
operation of
desired
class
91
Vehicle
changeGear
Land Vehicle
Car
1/25/16
Water Vehicle
Amphibious Vehicle
Boat
1/25/16
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
1/25/16
94
Kinds of Association
Class Association
Inheritance
Object Association
Simple Association
Composition
Aggregation
1/25/16
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
1/25/16
96
1/25/16
97
One-way Association
We can navigate along a single direction only
Denoted by an arrow towards the server object
1/25/16
98
Example Association
Ali
lives1 in
House
99
Example Association
Ali
drives
1
Car
100
Two-way Association
We can navigate in both directions
Denoted by a line between the associated objects
1/25/16
101
Company
102
Yasir
frien
1 d
Ali
103
Binary Association
Associates objects of exactly two classes
Denoted by a line, or an arrow between the associated
objects
1/25/16
104
Company
105
Ali
drives
1
Car
106
Ternary Association
Associates objects of exactly three classes
Denoted by a diamond with lines connected to
associated objects
1/25/16
107
Teacher
1
*
*
Course
Objects of exactly three classes are
associated
1/25/16
108
Language
*
1
Person
Objects of exactly three classes are
associated
1/25/16
109
N-ary Association
An association between 3 or more classes
Practical examples are very rare
1/25/16
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 filleddiamond head towards the composer object
1/25/16
111
Arm
Ali
Leg
1
Body
1/25/16
112
Chair
1/25/16
Arm
Seat
COMSATS Institute of Information Technology
4
Leg
113
Composition is Stronger
Composition is a stronger relationship, because
Composed object becomes a part of the composer
Composed object cant exist independently
1/25/16
114
1/25/16
115
1/25/16
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 unfilleddiamond head towards the container
1/25/16
117
Example Aggregation
Bed
1
Chair
Room
Table
1
Cupboard
1/25/16
118
Example Aggregation
Garden
1/25/16
Plant
119
Aggregation is Weaker
Aggregation is weaker relationship, because
Aggregate object is not a part of the container
Aggregate object can exist independently
1/25/16
120
1/25/16
121
1/25/16
122
1/25/16
References
123
Thanks
1/25/16
124
CSC241:
Object Oriented
Programming
Spring 2013
1. Inheritance Concepts
2. Polymorphism
1/25/16
Farhan Aadil
1/25/16
COMSATS
Intitute
of Information
TechnologyPhones!
Please
turn
OFF
your Mobile
125
1/25/16
126
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
1/25/16
127
Kinds of Association
Class Association
Inheritance
Object Association
Simple Association
Composition
Aggregation
1/25/16
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
1/25/16
129
1/25/16
130
One-way Association
We can navigate along a single direction only
Denoted by an arrow towards the server object
1/25/16
131
Example Association
Ali
lives1 in
House
132
Example Association
Ali
drives
1
Car
133
Two-way Association
We can navigate in both directions
Denoted by a line between the associated objects
1/25/16
134
Company
135
Yasir
frien
1 d
Ali
136
Binary Association
Associates objects of exactly two classes
Denoted by a line, or an arrow between the associated
objects
1/25/16
137
Company
138
Ali
drives
1
Car
139
Ternary Association
Associates objects of exactly three classes
Denoted by a diamond with lines connected to
associated objects
1/25/16
140
Teacher
1
*
*
Course
Objects of exactly three classes are
associated
1/25/16
141
Language
*
1
Person
Objects of exactly three classes are
associated
1/25/16
142
N-ary Association
An association between 3 or more classes
Practical examples are very rare
1/25/16
143
144
Composition
An object may be composed of other smaller objects
The relationship between the part objects and the
whole object is known as Composition
Composition is represented by a line with a filleddiamond head towards the composer object
1/25/16
145
146
Arm
Ali
Leg
1
Body
1/25/16
147
Chair
1/25/16
Arm
Seat
COMSATS Intitute of Information Technology
4
Leg
148
Composition is Stronger
Composition is a stronger relationship, because
Composed object becomes a part of the composer
Composed object cant exist independently
1/25/16
149
1/25/16
150
1/25/16
151
Composition
Composition is a consists of relationship.
COURSE_DATA consists of STUDENT_DATA (besides
other things).
STUDENT_DATA lifetime is the same as COURSE_DATA.
Part may belong to only one whole.
The lifetime of the part is the same as the lifetime of the
whole.
1/25/16
152
Aggregation
An object may contain a collection (aggregate) of other
objects
The relationship between the container and the
contained object is called aggregation
Aggregation is represented by a line with unfilleddiamond head towards the container
1/25/16
154
155
Example Aggregation
Bed
1
Chair
Room
Table
1
Cupboard
1/25/16
156
Example Aggregation
Garden
1/25/16
Plant
157
Aggregation is Weaker
Aggregation is weaker relationship, because
Aggregate object is not a part of the container
Aggregate object can exist independently
1/25/16
158
1/25/16
159
1/25/16
160
161
struct TEST
{
public:
int x;
}
struct TEST
{
private:
int x;
}
TEST var;
var.x = 10;
TEST var;
var.x = 10;
//error
162
}
1/25/16
163
struct TEST
{
private:
int x;
public:
void Setx(int val) { x = val; };
TEST var;
var.x = 10; //e
int y = var.x; //e
164
1/25/16
struct TEST {
private:
We can declare
int x;
member functions
public:
void Setx(int val);
inside the struct and
int Getx();
define them outside
}
as well using the
void TEST::Setx(int val) {
x = val;
name of struct to
}
resolve ambiguity.
int TEST::Getx() {
return x;
}
V. IMP: Note that this
main() {
allows us to separate
TEST var;
var.Setx(10);
header and
int y = var.Getx();
implementation
files!
National University of Computer
and Emerging
}
Sciences
165
Class Compatibility
A class is behaviorally compatible with another if it
supports all the operations of the other class
Such a class is called subtype
A class can be replaced by its subtype
1/25/16
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
1/25/16
167
Circle
radius
draw
computeArea
1/25/16
Line
length
draw
getLength
COMSATS Intitute of Information Technology
Triangle
angle
draw
computeArea
168
open
print
ASCII File
1/25/16
PDF File
PS File
169
Polymorphism
In general, polymorphism refers to existence of different
forms of a single entity
For example, both Diamond and Coal are different forms
of Carbon
1/25/16
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
1/25/16
171
Example Polymorphism
View
draw
Line
draw
1/25/16
Shape
draw
Circle
draw
Triangle
draw
172
Example Polymorphism
Editor
ASCII File
print
1/25/16
File
print
PDF File
print
PS File
print
173
Polymorphism Advantages
Messages can be interpreted in different
ways depending upon the receiver class
View
draw
Line
draw
1/25/16
Shape
draw
Circle
draw
Triangle
draw
174
Polymorphism Advantages
New classes can be added without changing
the existing model
View
Square
draw
1/25/16
draw
Line
draw
Shape
draw
Circle
draw
Triangle
draw
175
Polymorphism Advantages
In general, polymorphism is a powerful tool to develop
flexible and reusable systems
1/25/16
176
Object-Oriented Modeling
An Example
1/25/16
177
Problem Statement
Develop a graphic editor that can draw different
geometric shapes such as line, circle and triangle. User
can select, move or rotate a shape. To do so, editor
provides user with a menu listing different commands.
Individual shapes can be grouped together and can
behave as a single shape.
1/25/16
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.
1/25/16
179
Identify Classes
Eliminate irrelevant classes
Editor Very broad scope
User Out of system boundary
1/25/16
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
1/25/16
181
Identify Classes
Following classes have been identified:
Shape
Line
Circle
Triangle
Menu
1/25/16
Group
View
182
Group
Line
Circle
Menu
View
Triangle
1/25/16
183
Identify Associations
Extract verbs connecting objects
Individual shapes can be grouped together
Group consists of lines, circles, triangles
Group can also consists of other groups
(Composition)
1/25/16
184
Identify Associations
Verify access paths
View contains shapes
View contains
View contains
View contains
View contains
(Aggregation)
1/25/16
lines
circles
triangles
groups
185
Identify Associations
Verify access paths
Menu sends message to View
(Simple One-Way Association)
1/25/16
186
View
Shape
n
Line n
n
Circle
n
Group
Triangle
n
1/25/16
187
Identify Attributes
Extract properties of the object
From the problem statement
1/25/16
188
Identify Attributes
Extract properties of the object
From the domain knowledge
Line
Color
Vertices
Length
Circle
Color
Vertices
Radius
1/25/16
Triangle
Color
Vertices
Angle
Shape
Color
Vertices
COMSATS Intitute of Information Technology
189
Identify Attributes
Extract properties of the object
From the domain knowledge
Group
Menu
noOfObjects
View
Name
isOpen
noOfObjects
selected
1/25/16
190
View
noOfObjects
selected
Shape
color
n vertices
n
n
Line n
length
n
1/25/16
Circle
radius
n
Triangle
angle
n
n
Group
noOfObjects
n
COMSATS Intitute of Information Technology
191
Identify Operations
Extract verbs connected with an object
192
Identify Operations
Eliminate irrelevant operations
Develop out of system boundary
Behave have broad semantics
1/25/16
193
Identify Operations
Following are selected operations:
Line
Draw
Select
Move
Rotate
1/25/16
Circle
Draw
Select
Move
Rotate
194
Identify Operations
Following are selected operations:
Triangle
Draw
Select
Move
Rotate
1/25/16
Shape
Draw
Select
Move
Rotate
195
Identify Operations
Following are selected operations:
Group
Draw
Select
Move
Rotate
1/25/16
Menu
Open
Select
Move
Rotate
196
Identify Operations
Extract operations using domain
knowledge
View
Add
Remove
Group
Show
1/25/16
Select
Move
Rotate
197
View
noOfObjects
selected
Menu
name
isOpen
add()
remove()
group()
show()
select()
move()
rotate()
open()
select()
move()
rotate()
Line n
length
draw()
n
1/25/16
Shape
color
vertices
n
Triangle
angle
n
Circle
radius
draw()
draw()
select()
move()
rotate()
n
draw()
Group
noOfObjects
n
draw()
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
1/25/16
199
Identify Inheritance
By analyzing requirements
Individual shapes can be grouped together and can
behave as a single shape
Group inherits from Shape
1/25/16
200
1/25/16
201
1/25/16
202
1/25/16
203
1/25/16
204
1/25/16
205
Menu
name
isOpen
open()
select()
move()
rotate()
1/25/16
View
noOfObjects
selected
Shape
color
vertices
add()
remove()
group()
show()
select()
move()
rotate()
draw()
select()
move()
rotate()
Line
length
Circle
radius
Triangle
angle
draw()
draw()
draw()
Group
noOfObjects
draw()
206
View
noOfObjects
selected
Menu
name
isOpen
add()
remove()
group()
show()
select()
move()
rotate()
open()
select()
move()
rotate()
Line n
length
draw()
n
1/25/16
Shape
color
vertices
n
Triangle
angle
n
Circle
radius
draw()
draw()
select()
move()
rotate()
n
draw()
Group
noOfObjects
n
draw()
207
Class
Class is a tool to realize objects
Class is a tool for defining a new type
1/25/16
208
Example
Lion is an object
Student is an object
Both has some attributes and some behaviors
1/25/16
209
Uses
The problem becomes easy to understand
Interactions can be easily modeled
1/25/16
210
Type in C++
Mechanism for user defined types are
Structures
Classes
1/25/16
211
Abstraction
Only include details in the system that are required for
making a functional system
Relevant to our problem
Student
1/25/16
Name
Address
Sibling
Father Business
212
Syntax
DataType MemberVariable;
ReturnType MemberFunction();
Syntax
};
1/25/16
213
Example
1/25/16
Member Functions
class Student
{
int rollNo;
Member variables
char *name;
float CGPA;
char *address;
};
214
1/25/16
215
Example
Student aStudent;
aStudent.rollNo = 514;
aStudent.rollNo = -514; //Error
1/25/16
216
1/25/16
217
1/25/16
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
1/25/16
219
Example
class Student{
int rollNo;
void setRollNo(int
aNo);
};
Student aStudent;
aStudent.rollNo;
1/25/16
Error
220
1/25/16
struct TEST {
class TEST {
private:
private:
int x;
int x;
public:
public:
void Setx(int val) { x =
val; };
void Setx(int val) { x =
val; };
int Getx() { return x; };
}
int Getx() { return x; };
main() {
}
TEST var;
main() {
var.Setx(10);
TEST var;
int y = var.Getx();
var.Setx(10);
}
int y = var.Getx();
Replacing struct with class, does not have any affect!
}
This is the keyword
OOL
(C++)
for OOP!
Nationalthat
University
of Computer
and provide
Emerging
Sciences
221
1/25/16
class TEST {
int x;
void Setx(int val) { x =
val; };
int Getx() { return x; };
}
main() {
TEST var;
var.x = 10; //error
var.Setx(10); //error
int y = var.Getx(); //error
222
223
Access specifiers
1/25/16
224
Access specifiers
There are three access specifiers
public is used to tell that member can be accessed whenever
you have access to the object
private is used to tell that member can only be accessed
from a member function
protected to be discussed when we cover inheritance
1/25/16
225
Example
class Student{
private:
char * name;
int rollNo;
public:
void setName(char *);
void setRollNo(int);
...
};
1/25/16
Can be
accessed
outside class
226
Example
class Student{
...
int rollNo;
public:
void setRollNo(int aNo);
};
int main(){
Student aStudent;
aStudent.SetRollNo(1);
}
1/25/16
227
1/25/16
228
Example
class Student
{
char * name;
class Student
int RollNo;
private:
char * name;
};
int RollNo;
};
1/25/16
229
Example
class Student
{
char * name;
int RollNo;
void SetName(char *);
Error
};
Student aStudent;
aStudent.SetName(Ali);
1/25/16
230
Example
class Student
{
char * name;
int RollNo;
public:
void setName(char *);
};
Student aStudent;
aStudent.SetName(Ali);
1/25/16
231
abstract
0..*
inheritance
(is a)
1/25/16
static
private
232 of 21
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
1/25/16
233
References
234
Thanks
1/25/16
235
CSC241:
Object Oriented
Programming
Spring 2013
1. Inheritance Concepts
2. Polymorphism
1/25/16
Farhan Aadil
1/25/16
COMSATS
Intitute
of Information
TechnologyPhones!
Please
turn
OFF
your Mobile
236
Review
Class
Concept
Definition
Data members
Member Functions
Access specifier
Member Functions
Member functions are the functions that operate on the
data encapsulated in the class
Public member functions are the interface to the class
public:
ReturnType FunctionName() {
}
};
Example
Define a class of student
that has a roll number. This
class should have a
function that can be used
to set the roll number
Example
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){
rollNo = aRollNo;
}
};
public:
ReturnType FunctionName();
};
ReturnType ClassName::FunctionName()
{
Scope
resolution
}
operator
Example
class Student{
int rollNo;
public:
void setRollNo(int aRollNo);
};
void Student::setRollNo(int aRollNo){
rollNo = aRollNo;
}
Inline Functions
Instead of calling an inline function compiler replaces
the code at the function call point
Keyword inline is used to request compiler to make a
function inline
It is a request and not a command
Example
inline int Area(int len, int hi)
{
return len * hi;
}
int main()
{
cout << Area(10,20);
}
Inline Functions
If we define the function inside the class body then the
function is by default an inline function
In case function is defined outside the class body then
we must use the keyword inline to make a function
inline
Example
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){
rollNo = aRollNo;
}
};
Example
class Student{
public:
inline void setRollNo(int aRollNo);
};
void Student::setRollNo(int aRollNo){
rollNo = aRollNo;
}
Example
class Student{
public:
void setRollNo(int aRollNo);
};
inline void Student::setRollNo(int aRollNo){
rollNo = aRollNo;
}
Example
class Student{
public:
inline void setRollNo(int aRollNo);
};
inline void Student::setRollNo(int aRollNo){
rollNo = aRollNo;
}
Constructor
Constructor
Constructor is used to initialize the objects of a class
Constructor is used to ensure that object is in well
defined state at the time of creation
Constructor is automatically called when the object is
created
Constructor are not usually called explicitly
Constructor (contd.)
Constructor is a special function having same name as
the class name
Constructor does not have return type
Constructors are commonly public members
Example
class Student{
public:
Student(){
rollNo = 0;
}
};
Example
int main()
{
Student aStudent;
/*constructor is implicitly called at this
point*/
}
Default Constructor
Constructor without any argument is called default
constructor
If we do not define a default constructor the compiler
will generate a default constructor
This compiler generated default constructor initialize
the data members to their default values
Example
class Student
{
int rollNo;
char *name;
float GPA;
public:
//no constructors
};
Example
Compiler generated default constructor
{
rollNo = 0;
GPA = 0.0;
name = NULL;
}
Constructor Overloading
Constructors can have parameters
These parameters are used to initialize the data
members with user supplied data
Example
class Student{
public:
Student();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(int aRollNo, int aRollNo, float aGPA);
};
Example
Student::Student(int aRollNo,
char * aName){
if(aRollNo < 0){
rollNo = 0;
}
else {
rollNo = aRollNo;
}
Example
int main()
{
Student student1;
Student student2(Name);
Student student3(Name, 1);
Student student4(Name,1,4.0);
}
Constructor Overloading
Use default parameter value to reduce the writing effort
Example
Student::Student( char * aName = NULL,
int aRollNo= 0,
float aGPA = 0.0){
}
Is equivalent to
Student();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(char * Name, int aRollNo, float aGPA);
References
266
1/25/16
267
Thanks
1/25/16
268
CSC241:
Object Oriented
Programming
Spring 2013
1. Functions
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
Revision
Chapter 5 of book
1/25/16
270
Functions
1/25/16
Return type
1/25/16
272 arguments
Input
Functions
//demonstrates a simple function
#include <iostream>
using namespace std;
int cube(int x);
// function deration
int main(){
// tests the cube() function:
int n = 1;
Input Arguments
while (n != 0){
cin >> n;
cout
<< "\tcube(" << n << ") =
<< cube(n) << endl; // Calling a function
} // end of while loop
system("PAUSE"); return 0;
Return type
}//end of main
int cube( int x ){ // function definition
return x*x*x;
// returns cube of x:
}
// { function body }
1/25/16
273
Functions
1/25/16
274
Default Arguments
#include <iostream>
using namespace std;
//declaration with default arguments
void repchar(char='*', int=45);
int main(){
repchar(); //prints 45 asterisks
repchar('='); //prints 45 equal signs
repchar('+', 30); //prints 30 plus signs
system("PAUSE"); return 0;
}
// displays line of characters
void repchar(char ch, int n){
// defaults supplied if necessary
for(int j=0; j<n; j++)
// loops n times
cout << ch;
// prints ch
cout << endl;
}
1/25/16
275
Inline Function
1/25/16
276
Inline Function
// 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;
}
1/25/16
277
Recursion
1/25/16
278
Recursion
#include <iostream>
using namespace std;
// calls itself to calculate factorials
unsigned long fct(unsigned long n){
static int I = 0; I++;
cout << "You Called Me " << I << " times" << endl;
if(n > 1)
return n * fct(n-1); //self call
else
return 1;
}
int main(){
int n;
cout << "Enter an integer: "; cin >> n;
cout << "Factorial of " << n << " is " << fct(n) << "\n";
system("PAUSE"); return 0;
}
1/25/16
279
Recursion
1/25/16
280
References
1/25/16
281
Thanks
1/25/16
282
CSC241:
Object Oriented
Programming
Spring 2013
1. Constructors
1/25/16
Farhan Aadil
1/25/16
COMSATS
Intitute
of Information
TechnologyPhones!
Please
turn
OFF
your Mobile
283
Constructor
Constructor
Constructor is used to initialize the objects of a class
Constructor is used to ensure that object is in well
defined state at the time of creation (Lion 4 legs, Roll No
+ve int)
Constructor is automatically called when the object is
created
Constructor are not usually called explicitly
Constructor (contd.)
Constructor is a special function having same name as
the class name
Constructor does not have return type
Constructors are commonly public members
Example
class Student{
public:
Student(){
rollNo = 0;
}
};
Example
int main()
{
Student aStudent;
/*constructor is implicitly called at this
point*/
}
Default Constructor
Constructor without any argument is called default
constructor
If we do not define a default constructor the compiler
will generate a default constructor
This compiler generated default constructor initialize
the data members to their default values
Example
class Student
{
int rollNo;
char *name;
float GPA;
public:
//no constructors
};
Example
Compiler generated default constructor
{
rollNo = 0;
GPA = 0.0;
name = NULL;
}
Constructor Overloading
Constructors can have parameters
These parameters are used to initialize the data
members with user supplied data
Example
class Student{
public:
Student();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(char * aName, int aRollNo, float aGPA);
};
Example
Student::Student(int aRollNo,
char * aName){
if(aRollNo < 0){
rollNo = 0;
}
else {
rollNo = aRollNo;
}
Example
int main()
{
Student student1;
Student student2(Name);
Student student3(Name, 1);
Student student4(Name,1,4.0);
}
Constructor Overloading
Use default parameter value to reduce the writing effort
Example
Student::Student( char * aName = NULL,
int aRollNo= 0,
float aGPA = 0.0){
}
Is equivalent to
Student();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(char * Name, int aRollNo, float aGPA);
Copy Constructor
Copy constructor are used when:
Initializing an object at the time of creation
When an object is passed by value to a function
Example
void func1(Student student){
}
int main(){
Student studentA;
Student studentB = studentA;
func1(studentA);
}
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;
studentA
Name
RollNo
GPA
Memory
A
H
M
A
D
studentB
Name
RollNo
GPA
Assignment
Lab Assignment No 3
1/25/16
303
References
304
Thanks
1/25/16
305
CSC241:
Object Oriented
Programming
Spring 2013
1. Destructor
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
Review
Copy constructors
Destructor
this Pointer
Separation of interface and
implementation
Destructor
You might guess that another function is called
automatically when an object is destroyed.
This is indeed the case. Such a function is
called a destructor.
A destructor also has the same name as the
class name but is preceded by a tilde (~) sign:
Like constructors, destructors do not have a
return value. They also take no arguments.
The most common use of destructors is to deallocate memory that was allocated for the
object by the constructor.
1/25/16
308
Using Destructor
1/25/16
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
{
return
}
Student
{
return
}
Student::setRollNo(int aNo)
*this;
Student::setName(char *aName)
*this;
Example
int main()
{
Student aStudent;
Student bStudent;
bStudent = aStudent.setName(Ahmad);
bStudent = aStudent.setName(Ali).setRollNo(2);
return 0;
}
Complex Number
There are two representations of
complex number
Euler form
z = x + i y
Phasor form
Example
Old
implementation
Complex
float x
float y
float getX()
float getY()
void setNumber
(float i, float j)
New
implementation
Complex
float z
float theta
float getX()
float getY()
void setNumber
(float i, float j)
Example
class Complex{ //old
float x;
float y;
public:
void setNumber(float i, float j){
x = i;
y = j;
}
};
Example
class Complex{ //new
float z;
float theta;
public:
void setNumber(float i, float j){
theta = arctan(j/i);
};
Advantages
User is only concerned about ways of
accessing data (interface)
User has no concern about the internal
representation and implementation of
the class
Student.h
class Student{
int rollNo;
public:
void setRollNo(int aRollNo);
int getRollNo();
};
Student.cpp
#include student.h
void Student::setRollNo(int aNo){
}
int Student::getRollNo(){
Driver.cpp
#include student.h
int main(){
Student aStudent;
}
1/25/16
1/25/16
324
References
325
Thanks
1/25/16
326
CSC241:
Object Oriented
Programming
Spring 2013
1.Static class member
2.Const member function
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
328
int main()
{
foo f1, f2, f3; //create three objects
cout << count is << f1.getcount()
<< endl; //each object
cout << count is << f2.getcount()
<< endl; //sees the
cout << count is << f3.getcount()
<< endl; //same value
return 0;
}
{ return count;
}
};
1/25/16
329
330
331
332
1/25/16
333
int sz = sizeof(Counter);
OR
private:
unsigned char count;
unsigned char temp2;
Counter c1;
int sz = sizeof(c1);
short temp1;
Gives sz = 8
int temp;
334
335
Example
bool Student::isRollNo(int aNo){
if(rollNo = = aNo){
return true;
}
return false;
}
1/25/16
336
Example
bool Student::isRollNo(int aNo){
/*undetected typing mistake*/
if(rollNo = aNo){
return true;
}
return false;
}
1/25/16
337
Example
bool Student::isRollNo
(int aNo)const{
/*compiler error*/
if(rollNo = aNo){
return true;
}
return false;
}
1/25/16
338
1/25/16
339
}
1/25/16
340
Example
class Student{
public:
int getRollNo() const {
return rollNo;
}
};
1/25/16
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
1/25/16
342
const Functions
Constructors and Destructors cannot
be const
Constructor and destructor are used to
modify the object to a well defined
state
1/25/16
343
Example
class Time{
public:
Time() const {}
~Time() const {}
};
1/25/16
//error
//error
344
const Function
Constant member function cannot
change data member
Constant member function cannot
access non-constant member
functions
1/25/16
345
Example
class Student{
char * name;
public:
char *getName();
void setName(char * aName);
int ConstFunc() const{
name = getName();//error
setName(Ahmad);//error
}
};
1/25/16
346
1/25/16
347
References
348
Thanks
1/25/16
349
CSC241:
Object Oriented
Programming
Spring 2013
1.Arrays & String (Chapter 7)
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
Arrays
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;
}
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;
}
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
ary[0][0]= 0x22ff40 = 11
11 12 13
21 22 23
ary[0][1]= 0x22ff44 = 12
ary[0][2]= 0x22ff48 = 13
ary[1][0]= 0x22ff4C = 21
ary[1][1]= 0x22ff50 = 22
ary[1][2]= 0x22ff54 = 23
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;
}
ary[0][0]= 0x22ff30 = 11
3-Dimensional Arrays
ary[0][1]= 0x22ff34 = 12
ary[0][2]= 0x22ff38 = 13
ary[1][0]= 0x22ff3C = 21
11 12 13
21 22 23
31 32 33
ary[1][1]= 0x22ff40 = 22
ary[1][2]= 0x22ff44 = 23
ary[2][0]= 0x22ff48 = 31
ary[2][1]= 0x22ff4C = 32
ary[2][2]= 0x22ff50 = 33
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;
}
Array of Strings
// straray.cpp
// array of strings
#include <iostream>
using namespace std;
int main(){
const int DAYS = 7; //number of strings in array
const int MAX = 10; //maximum size of each string
//An array of strings
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday" , "Saturday" };
for( int j=0 ; j<DAYS ; j++) //display every string
cout << star[j] << endl;
system("PAUSE");
return 0;
}
Array of Strings
Lab Task
Write a and test a program to calculate Determinant and Reverse of a 3x3 matrix
References
376
Thanks
1/25/16
377
CSC241:
Object Oriented
Programming
Spring 2013
1.Composition
2.Aggregation
3.Friend Functions
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
Pointer to Objects
Pointer to objects are similar as pointer to built-in types
They can also be used to dynamically allocate objects
Example
class Student{
public:
Studen();
Student(char * aName);
void setRollNo(int aNo);
};
Example (Aggregation)
int main(){
Student obj;
Student *ptr;
ptr = &obj;
ptr->setRollNo(10);
return 0;
}
Example
int main(){
Student *ptr;
ptr = new Student;
ptr->setRollNo(10);
return 0;
}
Example
int main(){
Student *ptr;
ptr = new Student(Ali);
ptr->setRollNo(10);
return 0;
}
Case Study
Design a class date through which user must be able to
perform following operations
Get and set current day, month and year
Increment by x number of days, months and year
Set default date
Attributes
Attributes that can be seen in this problem statement
are
Day
Month
Year
Default date
Attributes
The default date is a feature shared by all objects
This attribute must be declared a static member
Attributes in Date.h
class Date
{
int day;
int month;
int year;
static Date defaultDate;
};
Interfaces
getDay
getMonth
getYear
setDay
setMonth
setYear
addDay
addMonth
addYear
setDefaultDate
Interfaces
As the default date is a static member the interface
setDefaultDate should also be declared static
Interfaces in Date.h
class Date{
public:
void setDay(int aDay);
int getDay() const;
void addDay(int x);
};
Interfaces in Date.h
class Date{
public:
static void setDefaultDate(
int aDay,int aMonth, int aYear);
};
Constructors
Date::Date(int aDay, int aMonth,
int aYear) {
if(aDay==0) {
this->day = defaultDate.day;
}
else{
setDay(aDay);
}
//similarly for other members
}
Destructor
We are not required to do any house keeping chores in
destructor
Date::~Date
{
}
addYear
void Date::addYear(int x){
year += x;
if(day == 29 && month == 2
&& !leapyear(year)){
day = 1;
month = 3;
}
}
Helper Function
class Date{
private:
bool leapYear(int x) const;
};
Helper Function
bool Date::leapYear(int x) const{
if((x%4 == 0 && x%100 != 0)
|| (x%400==0)){
return true;
}
return false;
}
setDefaultDate
void Date::setDefaultDate(
int d, int m, int y){
if(d >= 0 && d <= 31){
day = d;
}
Aggregation
Composition vs.
Aggregation
Chair
Chair()
DoSomething() : void
FoldChair() : bool
UnFoldChair() : bool
~Chair()
Aggregation
In aggregation, a pointer or reference to
an object is created inside a class
NOT
e.g:
Chairs can be moved inside or outside at
anytime
When Room is destroyed, the chairs may
or may not be destroyed
Aggregation
class Room{
private:
float area;
Chair * chairs[50];
Public:
Room();
void AddChair(Chair *, int chairNo);
Chair * GetChair(int chairNo);
bool FoldChair(int chairNo);
};
Aggregation
Room::Room(){
for(int i = 0; i < 50; i++)
chairs[i] = NULL;
}
void Room::AddChair(Chair *
chair1, int chairNo){
if(chairNo >= 0 && chairNo < 50)
chairs[chairNo] = chair1;
}
Aggregation
Chair * Room::GetChair(int chairNo){
if(chairNo >= 0 && chairNo < 50)
return chairs[chairNo];
else
return NULL;
}
bool Room::FoldChair(int chairNo){
if(chairNo >= 0 && chairNo < 50)
return chairs[chairNo]->FoldChair();
else
return false;
}
Aggregation
int main(){
Chair ch1;
{
Room r1;
r1.AddChair(&ch1, 1);
r1.FoldChair(1);
}
ch1.UnFoldChair(1);
return 0;
}
Friend
Functions
Friend
Functions
Global function:
void DoSomething(X obj){
obj.a = 3; //Error
obj.b = 4; //Error
}
Friend
Functions
Friend
Functions
Prototypes of friend
functions appear in the
class definition
But friend functions are
NOT member functions
Friend
Functions
Friend
Functions
Friend
Functions
If keyword friend is used in the
function definition, its 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;
};
Friend Classes
Example:
class X{
friend class Y;
private:
int x_var1, x_var2;
...
};
Friend Classes
class Y{
private:
int y_var1, y_var2;
X objX;
public:
void setX(){
objX.x_var1 = 1;
}
};
Friend Classes
int main(){
Y objY;
objY.setX();
return 0;
}
References
420
Thanks
1/25/16
421
Spring 2013
1.Operator Overloading
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
1/25/16
COMSATS Intitute of
Information Technology
CSC241:
Object Oriented
Programming
422
Operator overloading
COMSATS Intitute of
Information Technology
class Complex{
private:
double real, img;
public:
1/25/16
423
Operator overloading
COMSATS Intitute of
Information Technology
Complex Complex::Add(
const Complex & c1){
Complex t;
t.real = real + c1.real;
t.img = img + c1.img;
return t;
}
1/25/16
Function implementation:
424
Complex c3 = c1.Add(c2);
Adds the contents of c2 to c1 and assigns
it to c3 (copy constructor)
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
425
COMSATS Intitute of
Information Technology
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)))
1/25/16
Operator overloading
426
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
427
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
428
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
429
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
430
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
431
float x;
int y;
x = 102.02 + 0.09;
Y = 50 + 47;
COMSATS Intitute of
Information Technology
Example:
1/25/16
Operator overloading
432
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
433
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
434
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
435
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
436
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
437
COMSATS Intitute of
Information Technology
Associativity is NOT
changed due to
overloading
Following arithmetic
expression always is
evaluated from left to right:
c1 + c2 + c3 + c4
1/25/16
Operator overloading
438
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
439
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
440
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
441
COMSATS Intitute of
Information Technology
1/25/16
Operator overloading
442
COMSATS Intitute of
Information Technology
1/25/16
Binary operators
443
COMSATS Intitute of
Information Technology
General syntax:
Member function:
TYPE1 CLASS::operator B_OP(
TYPE2 rhs){
...
}
1/25/16
Binary operators
444
COMSATS Intitute of
Information Technology
General syntax:
Non-member function:
TYPE1 operator B_OP(TYPE2 lhs,
TYPE3 rhs){
...
}
1/25/16
Binary operators
445
1/25/16
Binary operators
COMSATS Intitute of
Information Technology
446
COMSATS Intitute of
Information Technology
Overloading + operator:
class Complex{
private:
double real, img;
public:
1/25/16
Binary operators
447
COMSATS Intitute of
Information Technology
Complex Complex::operator +(
const Complex & rhs){
Complex t;
t.real = real + rhs.real;
t.img = img + rhs.img;
return t;
}
1/25/16
Binary operators
448
COMSATS Intitute of
Information Technology
1/25/16
Binary operators
449
COMSATS Intitute of
Information Technology
1/25/16
Binary operators
450
COMSATS Intitute of
Information Technology
void Complex::operator+(const
Complex & rhs){
real = real + rhs.real;
img = img + rhs.img;
};
1/25/16
Binary operators
451
COMSATS Intitute of
Information Technology
1/25/16
Binary operators
452
COMSATS Intitute of
Information Technology
1/25/16
Binary operators
453
References
454
Thanks
1/25/16
455
CSC241:
Object Oriented
Programming
Spring 2013
1. Inheritance
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
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
1/25/16
457
UML Notation
1/25/16
Parent Class
Base Class
Child Class
Derived Class
458
Inheritance in C++
There are three types of inheritance in C++
Public
Private
Protected
1/25/16
459
IS A Relationship
IS A relationship is modeled with the help
of public inheritance
Syntax
class ChildClass
: public BaseClass{
...
};
1/25/16
460
Example
class Person{
...
};
class Student: public Person{
...
};
1/25/16
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)
1/25/16
462
Example
class Person{
char *name;
int age;
...
public:
const char *GetName() const;
int GetAge() const;
...
};
1/25/16
463
Example
class Student: public Person{
int semester;
int rollNo;
...
public:
int GetSemester() const;
int GetRollNo() const;
void Print() const;
...
};
1/25/16
464
Example
void Student::Print()
{
ERROR
cout << name << is in << semester
<< semester;
1/25/16
465
Example
void Student::Print()
{
cout << GetName()
<< is in semester
semester;
<<
1/25/16
466
Example
int main(){
Student stdt;
stdt.semester = 0;//error
stdt.name = NULL; //error
cout << stdt.GetSemester();
cout << stdt.GetName();
return 0;
}
1/25/16
467
Allocation in Memory
The object of derived class is represented
in memory as follows
base member1
base member2
...
Data members of
base class
468
Allocation in Memory
Every object of derived class has an
anonymous object of base class
1/25/16
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
1/25/16
470
Constructors
base member1
base member2
...
derived member1
derived member2
...
Derived class
constructor initializes
the derived class
object
1/25/16
471
Example
class Parent{
public:
Parent(){ cout <<
Parent Constructor...;}
};
class Child : public Parent{
public:
Child(){ cout <<
Child Constructor...;}
};
1/25/16
472
Example
int main(){
Child cobj;
return 0;
}
Output:
Parent Constructor...
Child Constructor...
1/25/16
473
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
1/25/16
474
Constructor
If the user has given only an
overloaded constructor for base
class, the compiler will not
generate default constructor for
base class
1/25/16
475
Example
class Parent{
public:
Parent(int i){}
};
class Child : public Parent{
public:
Child(){}
} Child_Object; //ERROR
1/25/16
476
1/25/16
477
Example
class Parent{
public:
Parent(int i){};
};
class Child : public Parent{
public:
Child(int i): Parent(i)
{}
};
1/25/16
478
Example
class Parent{
public:
Parent(){cout <<
Parent Constructor...;}
...
};
class Child : public Parent{
public:
Child():Parent()
{cout << Child Constructor...;}
...
};
1/25/16
479
1/25/16
480
Example
class Parent{
public:
Parent(){}
};
class Child : public Parent{
int member;
public:
Child():member(0), Parent()
{}
};
1/25/16
481
1/25/16
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
1/25/16
483
Example
class Person{
public:
int age;
char *name;
...
public:
Person();
};
1/25/16
484
Example
class Student: public Person{
private:
int semester;
...
public:
Student(int a):age(a)
{
//error
}
};
1/25/16
485
Reason
It will be an assignment not an initialization
1/25/16
486
Destructors
Destructors are called in reverse order of
constructor called
Derived class destructor is called before the
base class destructor is called
1/25/16
487
Example
class Parent{
public:
Parent(){cout <<Parent Constructor;}
~Parent(){cout<<Parent Destructor;}
};
class Child : public Parent{
public:
Child(){cout << Child Constructor;}
~Child(){cout << Child Destructo;}
};
1/25/16
488
Example
Output:
Parent Constructor
Child Constructor
Child Destructor
Parent Destructor
1/25/16
489
1/25/16
490
Date Class
class Date{
int day, month, year;
static Date defaultDate;
public:
void SetDay(int aDay);
int GetDay() const;
void AddDay(int x);
Date Class
...
private:
bool IsLeapYear();
};
int main(){
Date aDate;
aDate.IsLeapYear(); //Error
return 0;
}
Special Date
Special Date
AddSpecialYear
...
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
protected:
bool IsLeapYear();
};
int main(){
Date aDate;
aDate.IsLeapYear(); //Error
return 0;
}
Modified AddSpecialYear
void SpecialDate :: AddSpecialYear
(int i){
...
if(day == 29 && month == 2
&& !IsLeapyear(year+i)){
...
}
}
Disadvantages
Breaks encapsulation
The protected member is part of base classs
implementation as well as derived classs
implementation
References
502
Thanks
1/25/16
503
CSC241:
Object Oriented
Programming
Spring 2013
1. Inheritance
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
Hierarchy of Inheritance
We represent the classes involved in
inheritance relation in tree like hierarchy
1/25/16
505
Example
GrandParent
1/25/16
Parent1
Parent2
Child1
Child2
506
507
1/25/16
class GrandParent{};
class Parent1:
public GrandParent {};
class Child1:public Parent1{};
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
1/25/16
509
Example
class GrandParent{
int gpData;
public:
GrandParent() : gpData(0){...}
GrandParent(int i) : gpData(i){...}
void Print() const;
};
1/25/16
510
Example
class Parent1: public GrandParent{
int pData;
public:
Parent1() : GrandParent(),
pData(0) {}
};
1/25/16
511
Example
class Child1 : public Parent1 {
public:
Child1() : Parent1() {...}
Child1(int i) : GrandParent (i) //Error
{...}
void Print() const;
};
1/25/16
512
Overriding
Child class can override the function of GrandParent
class
1/25/16
513
Example
GrandParent
Print()
Parent1
Child1
Print()
1/25/16
514
Example
void GrandParent::Print() {
cout << GrandParent::Print
<< endl;
}
void Child1::Print() {
cout << Child1::Print << endl;
}
1/25/16
515
Example
int main(){
Child1 obj;
obj.Print();
obj.Parent1::Print();
obj.GrandParent::Print();
return 0;
}
1/25/16
516
Output
Output is as follows
Child1::Print
GrandParent::Print
GrandParent::Print
1/25/16
517
Types of Inheritance
There are three types of inheritance
Public
Protected
Private
1/25/16
518
Public Inheritance
class Child: public Parent {};
Member access in
Base Class
Derived Class
Public
Public
Protected
Protected
Private
Hidden
Protected Inheritance
class Child: protected Parent {};
Member access in
Base Class
Derived Class
Public
Protected
Protected
Protected
Private
Hidden
Private Inheritance
class Child: private Parent {};
Member access in
Base Class
Derived Class
Public
Private
Protected
Private
Private
Hidden
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 {}
1/25/16
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
1/25/16
523
Example
class Collection {
...
public:
void AddElement(int);
bool SearchElement(int);
bool SearchElementAgain(int);
bool DeleteElement(int);
};
1/25/16
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
1/25/16
525
Class Set
class Set: private Collection {
private:
...
public:
void AddMember(int);
bool IsMember(int);
bool DeleteMember(int);
};
1/25/16
526
Class Set
void Set::AddMember(int i){
if (! IsMember(i) )
AddElement(i);
}
bool Set::IsMember(int i){
return SearchElement(i);
}
1/25/16
527
References
528
Thanks
1/25/16
529
CSC241:
Object Oriented
Programming
Spring 2013
1. Private Inheritance
2. Specialization
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
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 {}
1/25/16
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
1/25/16
Example
class Collection {
...
public:
void AddElement(int);
bool SearchElement(int);
bool SearchElementAgain(int);
bool DeleteElement(int);
};
1/25/16
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
1/25/16
Class Set
class Set: private Collection {
private:
...
public:
void AddMember(int);
bool IsMember(int);
bool DeleteMember(int);
};
1/25/16
Class Set
void Set::AddMember(int i){
if (! IsMember(i) )
AddElement(i);
}
bool Set::IsMember(int i){
return SearchElement(i);
}
1/25/16
Specialization (Restriction)
the derived class is behaviourally incompatible with the
base class
Behaviourally incompatible means that base class cant
always be replaced by the derived class
1/25/16
Specialization (Restriction)
Specialization (Restriction) can be implemented using
private and protected inheritance
1/25/16
age = a
setAge( a )
Adult
age : [18..125]
setAge( a )
COMSATS Intitute of
Information Technology
Person
age : [0..125]
1/25/16
Private Inheritance
class Child: private Parent {};
Member access in
Base Class
Derived Class
Public
Private
Protected
Private
Private
Hidden
Example
class Person{
1/25/16
protected:
int age;
public:
bool SetAge(int _age){
if (_age >=0 && _age <= 125) {
age = _age;
return true;
}
return false;
}
COMSATS Intitute of Information Technology
};
Example
1/25/16
1/25/16
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().
1/25/16
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.
1/25/16
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.
1/25/16
References
Thanks
1/25/16
CSC241:
Object Oriented
Programming
Spring 2013
1.
2.
3.
4.
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
1/25/16
553
Overriding
Parent
...
Func1
Child
...
Func1
1/25/16
554
Overriding
class Parent {
public:
void Func1();
void Func1(int);
};
class Child: public Parent {
public:
void Func1();
};
1/25/16
555
1/25/16
556
Overriding
class Parent {
public:
void Func1();
void Func1();
//Error
};
1/25/16
557
1/25/16
558
Example
class Person{
public:
void Walk();
};
class ParalyzedPerson: public Person{
public:
void Walk();
};
1/25/16
559
1/25/16
560
Example
1/25/16
class Person{
char *name;
public:
Person(char *=NULL);
const char *GetName() const;
void Print(){
cout << Name: << name
<< endl;
}
};
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;
}
...
};
1/25/16
562
Example
int main(){
Student a(Ahmad, Computer
Science);
a.Print();
return 0;
}
1/25/16
563
Output
Output:
Name: Ahmed
Major: Computer Science
1/25/16
564
1/25/16
565
Example
class Student : public Person{
char * major;
public:
Student(char * aName, char* m);
void Print(){
Print();//Print of Person
cout<<Major: << major <<endl;
}
...
};
1/25/16
566
Example
int main(){
Student a(Ahmad, Computer
Science);
a.Print();
return 0;
}
1/25/16
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
1/25/16
568
Example
class Student : public Person{
char * major;
public:
Student(char * aName, char* m);
void Print(){
Person::Print();
cout<<Major: << major <<endl;
}
...
};
1/25/16
569
Example
int main(){
Student a(Ahmad, Computer
Science);
a.Print();
return 0;
}
1/25/16
570
Output
Output:
Name: Ahmed
Major: Computer Science
1/25/16
571
About the
Feed Back
Instructor
&
About the
1/25/16
Course
COMSATS Institute of Information Technology
572
Multiple Inheritance
A class can inherit from more then one class
1/25/16
573
Multiple Inheritance
Transmitter
...
Transmit()
Receiver
...
Receive()
Phone
1/25/16
574
Example
class Phone: public Transmitter,
public Receiver
{
...
};
1/25/16
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
1/25/16
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
1/25/16
577
Example
int main(){
Phone obj;
obj.Transmit();
obj.Receive();
return 0;
}
1/25/16
578
Multiple Inheritance
When using public multiple inheritance, the object of
derived class can replace the objects of all the base
classes
1/25/16
579
Example
int main(){
Phone obj;
Transmitter * tPtr = &obj;
Receiver * rPtr = &obj;
return 0;
}
1/25/16
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
1/25/16
581
Example
int main(){
Phone obj;
Transmitter * tPtr = &obj;
tPtr->Transmit();
tPtr->Receive();
//Error
return 0;
}
1/25/16
582
Example
int main(){
Phone obj;
Receiver * rPtr = &obj;
rPtr->Receive();
rPtr->Transmit(); //Error
return 0;
}
1/25/16
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
1/25/16
584
Multiple Inheritance
Land Vehicle
Car
1/25/16
Water Vehicle
Amphibiou
s Vehicle
COMSATS Institute of Information Technology
Boat
585
Example
class LandVehicle{
public:
int GetMaxLoad();
};
class WaterVehicle{
public:
int GetMaxLoad();
};
1/25/16
586
Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
};
int main(){
AmphibiousVehicle obj;
obj.GetMaxLoad(); // Error
return 0;
}
1/25/16
587
Multiple Inheritance
Programmer must explicitly specify the class name
when calling ambiguous function
1/25/16
588
Example
int main(){
AmphibiousVehicle obj;
obj.LandVehicle::GetMaxLoad();
obj.WaterVehicle::GetMaxLoad();
return 0;
}
1/25/16
589
Multiple Inheritance
The ambiguous call problem can arise when dealing
with multiple level of multiple inheritance
1/25/16
590
Multiple Inheritance
Vehicle
Land Vehicle
Car
1/25/16
Water Vehicle
Amphibiou
s Vehicle
COMSATS Institute of Information Technology
Boat
591
Example
class Vehicle{
public:
int GetMaxLoad();
};
class LandVehicle : public Vehicle{
};
class WaterVehicle : public Vehicle{
};
1/25/16
592
Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
};
int main(){
AmphibiousVehicle obj;
obj.GetMaxLoad(); // Error
return 0;
}
1/25/16
593
Example
int main()
{
AmphibiousVehicle obj;
obj.Vehicle::GetMaxLoad(); //Error
return 0;
}
Vehicle is accessible through two paths
1/25/16
594
Multiple Inheritance
Vehicle
Vehicle
Land Vehicle
Water Vehicle
Car
1/25/16
Amphibiou
s Vehicle
COMSATS Institute of Information Technology
Boat
595
Example
int main(){
AmphibiousVehicle obj;
obj.LandVehicle::GetMaxLoad();
obj.WaterVehicle::GetMaxLoad();
return 0;
}
1/25/16
596
Multiple Inheritance
Data member must be used with care when dealing with
more then one level on inheritance
1/25/16
597
Example
class Vehicle{
protected:
int weight;
};
class LandVehicle : public Vehicle{
};
class WaterVehicle : public Vehicle{
};
1/25/16
598
Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
public:
AmphibiousVehicle(){
LandVehicle::weight = 10;
WaterVehicle::weight = 10;
}
};
There are multiple copies of data member weight
1/25/16
599
COMSATS Institute of
Information Technology
1/25/16
Memory View
600
Virtual Inheritance
In virtual inheritance there is exactly one copy of the
anonymous base class object
1/25/16
601
Example
class Vehicle{
protected:
int weight;
};
class LandVehicle :
public virtual Vehicle{
};
class WaterVehicle :
public virtual Vehicle{
};
1/25/16
602
Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
public:
AmphibiousVehicle(){
weight = 10;
}
};
1/25/16
603
Memory View
Data Members of Vehicle
Data Members
Data Members
of
of LandVehicle
WaterVehicle
Data Members of
AmphibiousVehicle
1/25/16
604
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
1/25/16
605
Example
Student
GPA
MS/PhD Student
1/25/16
606
References
607
Thanks
1/25/16
608
CSC241:
Object Oriented
Programming
Spring 2013
1. Generic Programming
2. Templates
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!
Quiz
Explain Diamond of Death with help of Class Diagram,
also write code for your class diagram.
1/25/16
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??
1/25/16
611
Feed Back
Tough time , assignments, project why us????
Dont 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 speedWhy, 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
1/25/16
612
Motivation
Following function prints an array of integer elements:
void printArray(int* array, int size)
{
for ( int i = 0; i < size; i++ )
cout << array[ i ] << , ;
}
...Motivation
What if we want to print an array of characters?
void printArray(char* array,
int size)
{
for ( int i = 0; i < size; i++ )
cout << array[ i ] << , ;
}
...Motivation
What if we want to print an array of doubles?
void printArray(double* array,
int size)
{
for ( int i = 0; i < size; i++ )
cout << array[ i ] << , ;
}
...Motivation
Now if we want to change the way function prints the
array. e.g. from
1, 2, 3, 4, 5
to
1-2-3-4-5
...Motivation
Now consider the Array class that wraps an array of
integers
class Array {
int* pArray;
int size;
public:
};
...Motivation
What if we want to use an Array class that wraps arrays
of double?
class Array {
double* pArray;
int size;
public:
};
...Motivation
What if we want to use an Array class that wraps arrays
of boolean variables?
class Array {
bool* pArray;
int size;
public:
};
...Motivation
Now if we want to add a function sum to Array class,
we have to change all the three classes
Generic Programming
Generic programming refers to programs containing
generic abstractions
A generic program abstraction (function, class) can be
parameterized with a type
Such abstractions can work with many different types of
data
Advantages
Reusability
Writability
Maintainability
Templates
In C++ generic programming is done using templates
Two kinds
Function Templates
Class Templates
Function Templates
A function template can be parameterized to operate on
different types of data
Declaration
template< class T >
void funName( T x );
// OR
template< typename T >
void funName( T x );
// OR
template< class T, class U, >
void funName( T x, U y, );
// Error!
double y;
y = getInput();
}
// Error!
User-defined Specializations
A template may not handle all the types successfully
Explicit specializations need to be provided for specific
type(s)
References
637
Thanks
1/25/16
638
LEC 20 TEMPLATE.CPP
// function template
#include <iostream>
using namespace std;
template <class T>
T GetMax (T a, T b)
{
T result;
result = (a>b)? a : b;
return (result);
}
int main ()
{
int i=5, j=6, k;
float l=10.5, m=5.6, n;
k=GetMax< int >(i,j);
n=GetMax< float >(l,m);
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): ";