Sei sulla pagina 1di 636

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

COMSATS Institute of Information Technology

Procedural vs. Object-Oriented


Procedural

Object Oriented

Customer, money, account


1/25/16

Withdraw, deposit, transfer

COMSATS Institute of Information Technology

Object-Orientation
(OO)

1/25/16

COMSATS Institute of Information Technology

What is Object-Orientation?
A technique for system modeling
OO model consists of several interacting objects

1/25/16

COMSATS Institute of Information Technology

What is a Model?
A model is an abstraction of something
Purpose is to understand the product before developing
it

1/25/16

COMSATS Institute of Information Technology

Examples Model
Highway maps
Architectural models
Mechanical models

1/25/16

COMSATS Institute of Information Technology

Example OO Model

1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

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

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)

1/25/16

COMSATS Institute of Information Technology

12

What is an Object?
An object has
State (attributes)
Well-defined behaviour (operations)
Unique identity

1/25/16

COMSATS Institute of Information Technology

13

Example Ali is a Tangible Object


State (attributes)
Name
Age

behaviour (operations)
Walks
Eats

Identity
His name

1/25/16

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
1/25/16

COMSATS Institute of Information Technology

15

Example Time is an Object


Apprehended Intellectually
State (attributes)
- Hours
- Minutes

- Seconds

behaviour (operations)
- Set Hours
- Set Minutes

- Set Seconds

Identity
- Would have a unique ID in the model

1/25/16

COMSATS Institute of Information Technology

16

Example Date is an Object


Apprehended Intellectually
State (attributes)
- Year
- Month

- Day

behaviour (operations)
- Set Year
- Set Day
- Set Month

Identity
- Would have a unique ID in the model

1/25/16

COMSATS Institute of Information Technology

17

Definition
What Is an Object?
An object is a software bundle of related variables and
methods. Software objects are often used to model 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

COMSATS Institute of Information Technology

18

Real-world objects share two


characteristics
They all have state and behavior
dogs have state (name, color, breed, hungry) and
behavior (barking, fetching, and wagging tail).
Bicycles have state (current gear, current pedal
cadence, two wheels, number of gears) and behavior
(braking, accelerating, slowing down, changing gears).

1/25/16

COMSATS Institute of Information Technology

19

Software objects are modeled after realworld 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.

1/25/16

COMSATS Institute of Information Technology

20

Can represent real-world objects by


using software objects.
You might want to represent real-world dogs as software
objects in an animation program or a real-world bicycle
as a software object in the program that controls an
electronic exercise bike.
You can also use software objects to model abstract
concepts. For example, an event is a common object
used in GUI window systems to represent the action of a
user pressing a mouse button or a key on the keyboard.

1/25/16

COMSATS Institute of Information Technology

21

Moving to new thinking


C is a procedural language. A procedure is
a list of instructions.
Very small programs (tens of lines) need no
organization.
As they get large (hundreds of lines), they are
divided into functions.
Functions are still lists of instructions.
Dividing a program into functions gives a
structure to the program (hence structured
programming).
1/25/16

COMSATS Institute of Information Technology

22

Moving to new thinking


C programming cannot do the following well:
Functions have unrestricted access to global data.
Data and Functions are unrelated; they do not
form a logical group or show any form of binding.
Cannot model real world.

In real world, we deal with objects like cars,


people etc.
Are such objects like data? Which data type
describes a car, for example?
Are such objects like functions? What will a
function car() do?
1/25/16

COMSATS Institute of Information Technology

23

Moving to new thinking


A real world object, e.g. car:
Is its description purely the ability to have a
data type to represent its specifications or
attributes only? For example what attributes
describe a car?
So by having all these attributes only do you
know all about a car? Would you buy a car by
merely looking at these attributes and their
values?
No! What else do you wish to have?

1/25/16

COMSATS Institute of Information Technology

24

Moving to new thinking


A real world object, e.g. car:
Test drive! Right?
What would you know through a test drive: how
it behaves in response to various stimulus!
How can it negotiate a speed braker, a speedy turn,
full braking etc.

Effectively, you wish to know how it functions.


Behaviour is like a function.

So neither data nor functions, by


themselves, model real-world objects
effectively.
1/25/16

COMSATS Institute of Information Technology

25

Object Oriented Approach


Neither data nor functions, by themselves, model
real-world objects effectively.
OO languages (like C++) combine both data and
functions that operate on that data into a single
unit, called object. Hence encapsulating an entity.
The objects functions are called member functions.
Typically, data can be accessed through functions
only. So data gets hidden.
Data hiding ensures the data is not accidentally
altered.
Reference analogy of a growing company; 2 people
vs 100 employee company.
Objects communicate with each other by calling
each others member functions.
1/25/16

COMSATS Institute of Information Technology

26

Object Oriented Approach


OOP is all about organization and not about
program operation. Most individual
statements are similar to C statements.
Member functions may be very similar to C
procedural functions.
In C you used to think about functions.
In C++ you should think about objects.
Often objects in C++ are real-world analogies.
In C++ objects are instances of classes.
E.g. Honda City is an instance of class car!
Class serves as a cookie cutter and an object
a cookie.
1/25/16

COMSATS Institute of Information Technology

27

Abstraction
Abstraction is a way to cope with complexity.
Principle of abstraction:
Capture only those details about an object that are
relevant to current perspective

1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

29

Example Abstraction
Ali is a PhD student and teaches BS
students
behaviour
-

1/25/16

Study
- DevelopExam
GiveExam
- TakeExam
PlaySports
- Eat
DeliverLecture
- Walk

COMSATS Institute of Information Technology

30

Example Abstraction
Students Perspective

Attributes

1/25/16

Name
Student Roll No
Year of Study
CGPA

- Employee ID
- Designation
- Salary
- Age

COMSATS Institute of Information Technology

31

Example Abstraction
Students Perspective
behaviour
-

1/25/16

Study
- DevelopExam
GiveExam
- TakeExam
PlaySports
- Eat
DeliverLecture
- Walk

COMSATS Institute of Information Technology

32

Example Abstraction
Teachers Perspective
Attributes
-

1/25/16

Name
Student Roll No
Year of Study
CGPA

- Employee ID
- Designation
- Salary
- Age

COMSATS Institute of Information Technology

33

Example Abstraction
Teachers Perspective
behaviour
-

1/25/16

Study
- DevelopExam
GiveExam
- TakeExam
PlaySports
- Eat
DeliverLecture
- Walk

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

35

Example Abstraction

Engineers View
Drivers View

1/25/16

COMSATS Institute of Information Technology

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

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

1/25/16

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

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

40

Graphical Representation of Classes


(Class Name)
(attributes)
(operations)

(Class Name)
Suppressed
Form

Normal
Form
1/25/16

COMSATS Institute of Information Technology

41

Example Graphical Representation of


Classes
Circle
center
radius
draw
computeArea

Circle
Suppressed
Form

Normal
Form
1/25/16

COMSATS Institute of Information Technology

42

Example Graphical Representation of


Classes
Person
name
age
gender
eat
walk

Person
Suppressed
Form

Normal
Form
1/25/16

COMSATS Institute of Information Technology

43

Inheritance
A child inherits characteristics of its parents
Besides inherited characteristics, a child may have its
own unique characteristics

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

45

Example Inheritance
Person

Student

1/25/16

Teacher

COMSATS Institute of Information Technology

Doctor

46

Example Inheritance
Shape

Line

1/25/16

Circle

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

48

Example IS A Relationship
Person

name
age
gender
eat
walk

Student

1/25/16

program
studyYear
study
heldExam

Teacher
designation
salary
teach
takeExam

COMSATS Institute of Information Technology

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

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

1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

55

1/25/16

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

COMSATS Institute of Information Technology

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]

56

Thanks

1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

59

Concepts Related with Inheritance


Generalization
Subtyping (extension)
Specialization (restriction)

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

61

Example Generalization
Line
color
vertices
length
move
setColor
getLength

1/25/16

Circle

color
vertices
radius
move
setColor
computeArea

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

Doctor
designation
salary
checkUp
prescribe
65

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

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

67

Person
name
age
gender
eats
walks

Example
Sub-typing
(Extension)

1/25/16

Student
program
studyYear
study
takeExam

COMSATS Institute of Information Technology

68

Shape
color
vertices
setColor
move

Example
Sub-typing
(Extension)

Circle
radius
computeCF
computeArea

1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

70

Example Specialization (Restriction)


Person
age : [0..100]

setAge( a )

Adult

1/25/16

age : [18..100]

setAge( a )

age = a

If age < 18 then


error
else
age = a

COMSATS Institute of Information Technology

71

Example Specialization (Restriction)


IntegerSet

add( elem )

NaturalSet

add( elem )

1/25/16

add
element to
the set
If elem < 1
then
error
else
add
element to
the set

COMSATS Institute of Information Technology

72

Overriding
A class may need to override the default behaviour
provided by its base class
Reasons for overriding

1/25/16

Provide behaviour specific to a derived class


Extend the default behaviour
Restrict the default behaviour
Improve performance
COMSATS Institute of Information Technology

73

Example Specific Behaviour


Shape

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

COMSATS Institute of Information Technology

76

Example Improve Performance


Shape
Class Circle
overrides rotate
operation of class
Shape with a Null
operation.

color
coord
draw
rotate
setColor

Circle

radius
draw
rotate
1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

78

Example Abstract Classes


Person
name
age
gender
eat
walk

Student

1/25/16

Teacher

Doctor

Here, Person
is an abstract class
COMSATS Institute of Information Technology

79

Example Abstract Classes


Vehicle
color
model
accelerate
applyBrakes

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

COMSATS Institute of Information Technology

81

Example Concrete Classes


Person
Student
program
studyYear
study
heldExam

1/25/16

Teacher

Doctor

Here, Student, Teacher and Doctor are


concrete classes
COMSATS Institute of Information Technology
82

Example Concrete Classes


Vehicle
Car

1/25/16

Bus

Truck
capacity
load
unload

Here, Car, Bus and Truck are


concrete classes
COMSATS Institute of Information Technology

83

Multiple Inheritance
We may want to reuse characteristics of more than one
parent class

1/25/16

COMSATS Institute of Information Technology

84

Example Multiple Inheritance

1/25/16

Mermai

COMSATS Institute of Information Technology

85

Example Multiple Inheritance

Woman

Fish

Mermaid

1/25/16

COMSATS Institute of Information Technology

86

Example Multiple Inheritance

Amphibious
Vehicle
1/25/16

COMSATS Institute of Information Technology

87

Example Multiple Inheritance


Vehicle
Land Vehicle

Car
1/25/16

Water Vehicle

Amphibious Vehicle
COMSATS Institute of Information Technology

Boat
88

Problems with Multiple Inheritance


Increased complexity
Reduced understanding
Duplicate features

1/25/16

COMSATS Institute of Information Technology

89

Problem Duplicate Features


Woman

eat

eat

Fish

Mermaid
Which eat operation Mermaid inherits?
1/25/16

COMSATS Institute of Information Technology

90

Solution Override the Common


Feature
Woman

eat

eat

Mermaid

eat

1/25/16

COMSATS Institute of Information Technology

Fish

Invoke eat
operation of
desired
class
91

Problem Duplicate Features (Diamond Problem)

Vehicle
changeGear

Land Vehicle

Car

1/25/16

Water Vehicle

Amphibious Vehicle

Boat

Which changeGear operation Amphibious


Vehicle inherits?
COMSATS Institute of Information Technology
92

Solution to Diamond Problem


Some languages disallow diamond
hierarchy
Others provide mechanism to ignore
characteristics from one side

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

94

Kinds of Association
Class Association
Inheritance

Object Association
Simple Association
Composition
Aggregation

1/25/16

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

1/25/16

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

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

98

Example Association

Ali

lives1 in

House

Ali lives in a House


1/25/16

COMSATS Institute of Information Technology

99

Example Association

Ali

drives
1

Car

Ali drives his Car


1/25/16

COMSATS Institute of Information Technology

100

Two-way Association
We can navigate in both directions
Denoted by a line between the associated objects

1/25/16

COMSATS Institute of Information Technology

101

Example Two-way Association


worksEmployee
* for

Company

Employee works for company


Company employs employees
1/25/16

COMSATS Institute of Information Technology

102

Example Two-way Association

Yasir

frien
1 d

Ali

Yasir is a friend of Ali


Ali is a friend of Yasir
1/25/16

COMSATS Institute of Information Technology

103

Binary Association
Associates objects of exactly two classes
Denoted by a line, or an arrow between the associated
objects

1/25/16

COMSATS Institute of Information Technology

104

Example Binary Association


worksEmployee
* for

Company

Association works-for associates objects of


exactly two classes
1/25/16

COMSATS Institute of Information Technology

105

Example Binary Association

Ali

drives
1

Car

Association drives associates objects of


exactly two classes
1/25/16

COMSATS Institute of Information Technology

106

Ternary Association
Associates objects of exactly three classes
Denoted by a diamond with lines connected to
associated objects

1/25/16

COMSATS Institute of Information Technology

107

Example Ternary Association


Student

Teacher
1

*
*

Course
Objects of exactly three classes are
associated
1/25/16

COMSATS Institute of Information Technology

108

Example Ternary Association


Project *

Language
*
1

Person
Objects of exactly three classes are
associated
1/25/16

COMSATS Institute of Information Technology

109

N-ary Association
An association between 3 or more classes
Practical examples are very rare

1/25/16

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 filleddiamond head towards the composer object

1/25/16

COMSATS Institute of Information Technology

111

Example Composition of Ali


Head
1

Arm

Ali

Leg

1
Body
1/25/16

COMSATS Institute of Information Technology

112

Example Composition of Chair


Back
1

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

COMSATS Institute of Information Technology

114

Example Composition is Stronger


Ali is made up of different body parts
They cant exist independent of Ali

1/25/16

COMSATS Institute of Information Technology

115

Example Composition is Stronger


Chairs body is made up of different parts
They cant exist independently

1/25/16

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 unfilleddiamond head towards the container

1/25/16

COMSATS Institute of Information Technology

117

Example Aggregation
Bed
1

Chair

Room

Table

1
Cupboard
1/25/16

COMSATS Institute of Information Technology

118

Example Aggregation

Garden

1/25/16

COMSATS Institute of Information Technology

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

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

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

122

1/25/16

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

COMSATS Institute of Information Technology

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]

123

Thanks

1/25/16

COMSATS Institute of Information Technology

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

Class diagram showing


inheritance
Inheritance among
classes is shown as
open triangular
arrowhead in UML
Class Diagram.
Arrow be read as
derived from.

1/25/16

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

127

Kinds of Association
Class Association
Inheritance

Object Association
Simple Association
Composition
Aggregation

1/25/16

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

1/25/16

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

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

131

Example Association

Ali

lives1 in

House

Ali lives in a House


1/25/16

COMSATS Intitute of Information Technology

132

Example Association

Ali

drives
1

Car

Ali drives his Car


1/25/16

COMSATS Intitute of Information Technology

133

Two-way Association
We can navigate in both directions
Denoted by a line between the associated objects

1/25/16

COMSATS Intitute of Information Technology

134

Example Two-way Association


worksEmployee
* for

Company

Employee works for company


Company employs employees
1/25/16

COMSATS Intitute of Information Technology

135

Example Two-way Association

Yasir

frien
1 d

Ali

Yasir is a friend of Ali


Ali is a friend of Yasir
1/25/16

COMSATS Intitute of Information Technology

136

Binary Association
Associates objects of exactly two classes
Denoted by a line, or an arrow between the associated
objects

1/25/16

COMSATS Intitute of Information Technology

137

Example Binary Association


worksEmployee
* for

Company

Association works-for associates objects of


exactly two classes
1/25/16

COMSATS Intitute of Information Technology

138

Example Binary Association

Ali

drives
1

Car

Association drives associates objects of


exactly two classes
1/25/16

COMSATS Intitute of Information Technology

139

Ternary Association
Associates objects of exactly three classes
Denoted by a diamond with lines connected to
associated objects

1/25/16

COMSATS Intitute of Information Technology

140

Example Ternary Association


Student

Teacher
1

*
*

Course
Objects of exactly three classes are
associated
1/25/16

COMSATS Intitute of Information Technology

141

Example Ternary Association


Project *

Language
*
1

Person
Objects of exactly three classes are
associated
1/25/16

COMSATS Intitute of Information Technology

142

N-ary Association
An association between 3 or more classes
Practical examples are very rare

1/25/16

COMSATS Intitute of Information Technology

143

Class diagram showing


association

Association among classes is shown as a simple arrow (ray) in UML


(Unified Modeling Language) Class Diagram.
The direction of arrow shows navigability.
time12 calls time24.
This is unidirectional association.
If both classes call operation of the other, navigability is both sided
(bidirectional association).
1/25/16

COMSATS Intitute of Information Technology

144

Composition
An object may be composed of other smaller objects
The relationship between the part objects and the
whole object is known as Composition
Composition is represented by a line with a filleddiamond head towards the composer object

1/25/16

COMSATS Intitute of Information Technology

145

Class diagram showing


composition

Composition among classes is shown as solid diamond


arrowhead in UML Class Diagram.
1/25/16

COMSATS Intitute of Information Technology

146

Example Composition of Ali


Head
1

Arm

Ali

Leg

1
Body
1/25/16

COMSATS Intitute of Information Technology

147

Example Composition of Chair


Back
1

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

COMSATS Intitute of Information Technology

149

Example Composition is Stronger


Ali is made up of different body parts
They cant exist independent of Ali

1/25/16

COMSATS Intitute of Information Technology

150

Example Composition is Stronger


Chairs body is made up of different parts
They cant exist independently

1/25/16

COMSATS Intitute of Information Technology

151

Composition
Composition is a consists of relationship.
COURSE_DATA consists of STUDENT_DATA (besides
other things).
STUDENT_DATA lifetime is the same as COURSE_DATA.
Part may belong to only one whole.
The lifetime of the part is the same as the lifetime of the
whole.

1/25/16

National University of Computer and Emerging


Sciences

152

Aggregation
An object may contain a collection (aggregate) of other
objects
The relationship between the container and the
contained object is called aggregation
Aggregation is represented by a line with unfilleddiamond head towards the container

1/25/16

COMSATS Intitute of Information Technology

154

Class diagram showing


aggregation

Aggregation among classes is shown as open diamond


arrowhead in UML Class Diagram.
1/25/16

COMSATS Intitute of Information Technology

155

Example Aggregation
Bed
1

Chair

Room

Table

1
Cupboard
1/25/16

COMSATS Intitute of Information Technology

156

Example Aggregation

Garden

1/25/16

COMSATS Intitute of Information Technology

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

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

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

160

More about struct


More on data hiding
By default all the data members of struct are
accessible (through the struct variable/object)
This behaviour is known as data being
public.
We can hide them by explicitly marking them
as private.
public: data or functions, can be accessed
from anywhere, outside or inside.
private: data or functions, cannot be
accessed from outside.
1/25/16

National University of Computer and Emerging


Sciences

161

More about struct


struct TEST
{
int x;
}
TEST var;
var.x = 10;
1/25/16

struct TEST
{
public:
int x;
}

struct TEST
{
private:
int x;
}

TEST var;
var.x = 10;

TEST var;
var.x = 10;
//error

National University of Computer and Emerging


Sciences

162

More about struct


struct stack {
int data[100];
int top;
} S;
///////////////////////////////////

void push(stack S, int a){


assert(top<100);
S.data[top]=a; S.top++;

}
1/25/16

COMSATS Intitute of Information Technology

163

More about struct


struct TEST
{
private:
int x;
}

struct TEST
{
private:
int x;
public:
void Setx(int val) { x = val; };

TEST var;
var.x = 10; //e
int y = var.x; //e

int Getx() { return x; };


}
TEST var;
var.Setx(10);
int y = var.Getx();

So even legitimate access of data goes through an


interface! We have secured the data further!!!
1/25/16

National University of Computer and Emerging


Sciences

164

Member functions definition

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

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

1/25/16

COMSATS Intitute of Information Technology

167

Example Class Compatibility


Shape
color
vertices
move
setColor
draw

Circle
radius
draw
computeArea
1/25/16

Line
length
draw
getLength
COMSATS Intitute of Information Technology

Triangle
angle
draw
computeArea
168

Example Class Compatibility


File
size

open
print

ASCII File

print

1/25/16

PDF File

print

COMSATS Intitute of Information Technology

PS File

print

169

Polymorphism
In general, polymorphism refers to existence of different
forms of a single entity
For example, both Diamond and Coal are different forms
of Carbon

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

171

Example Polymorphism
View

draw

Line
draw

1/25/16

Shape
draw
Circle
draw

COMSATS Intitute of Information Technology

Triangle
draw

172

Example Polymorphism
Editor

print

ASCII File
print

1/25/16

File
print
PDF File
print

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

Triangle
draw
175

Polymorphism Advantages
In general, polymorphism is a powerful tool to develop
flexible and reusable systems

1/25/16

COMSATS Intitute of Information Technology

176

Object-Oriented Modeling
An Example

1/25/16

COMSATS Intitute of Information Technology

177

Problem Statement
Develop a graphic editor that can draw different
geometric shapes such as line, circle and triangle. User
can select, move or rotate a shape. To do so, editor
provides user with a menu listing different commands.
Individual shapes can be grouped together and can
behave as a single shape.

1/25/16

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.

1/25/16

COMSATS Intitute of Information Technology

179

Identify Classes
Eliminate irrelevant classes
Editor Very broad scope
User Out of system boundary

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

181

Identify Classes
Following classes have been identified:
Shape
Line
Circle
Triangle
Menu

1/25/16

Group
View

COMSATS Intitute of Information Technology

182

Object Model Graphic Editor


Shape

Group

Line

Circle

Menu

View
Triangle

1/25/16

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

185

Identify Associations
Verify access paths
Menu sends message to View
(Simple One-Way Association)

1/25/16

COMSATS Intitute of Information Technology

186

Object Model Graphic Editor


Menu

View

Shape
n

Line n

n
Circle

n
Group

Triangle
n

1/25/16

COMSATS Intitute of Information Technology

187

Identify Attributes
Extract properties of the object
From the problem statement

Properties are not mentioned

1/25/16

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

190

Object Model Graphic Editor


Menu
name
isOpen

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

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

COMSATS Intitute of Information Technology

192

Identify Operations
Eliminate irrelevant operations
Develop out of system boundary
Behave have broad semantics

1/25/16

COMSATS Intitute of Information Technology

193

Identify Operations
Following are selected operations:

Line
Draw
Select
Move
Rotate

1/25/16

Circle
Draw
Select
Move
Rotate

COMSATS Intitute of Information Technology

194

Identify Operations
Following are selected operations:

Triangle
Draw
Select
Move
Rotate

1/25/16

Shape
Draw
Select
Move
Rotate

COMSATS Intitute of Information Technology

195

Identify Operations
Following are selected operations:

Group
Draw
Select
Move
Rotate

1/25/16

Menu
Open
Select
Move
Rotate

COMSATS Intitute of Information Technology

196

Identify Operations
Extract operations using domain
knowledge

View
Add
Remove
Group
Show

1/25/16

Select
Move
Rotate

COMSATS Intitute of Information Technology

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()

COMSATS Intitute of Information Technology

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

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

1/25/16

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,

1/25/16

All attributes are shared


All associations are shared
Some operations are shared
Others are overridden

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

1/25/16

COMSATS Intitute of Information Technology

202

Refining the Object Model


Share attributes
Shape Line, Circle, Triangle and Group
Color, vertices

1/25/16

COMSATS Intitute of Information Technology

203

Refining the Object Model


Share operations
Shape Line, Circle, Triangle and Group
Select
Move
Rotate

1/25/16

COMSATS Intitute of Information Technology

204

Refining the Object Model


Share the interface and override implementation
Shape Line, Circle, Triangle and Group
Draw

1/25/16

COMSATS Intitute of Information Technology

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()

COMSATS Intitute of Information Technology

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()

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

208

Example
Lion is an object
Student is an object
Both has some attributes and some behaviors

1/25/16

COMSATS Intitute of Information Technology

209

Uses
The problem becomes easy to understand
Interactions can be easily modeled

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

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

Not relevant to our problem

COMSATS Intitute of Information Technology

212

Defining a New User Defined Type


class ClassName
{

Syntax

DataType MemberVariable;
ReturnType MemberFunction();
Syntax

};
1/25/16

COMSATS Intitute of Information Technology

213

Example

1/25/16

COMSATS Intitute of Information Technology

Member Functions

class Student
{
int rollNo;
Member variables
char *name;
float CGPA;
char *address;

void setName(char *newName);


void setRollNo(int newRollNo);

};

214

Why Member Function


They model the behaviors of an object
Objects can make their data invisible
Object remains in consistent state

1/25/16

COMSATS Intitute of Information Technology

215

Example
Student aStudent;
aStudent.rollNo = 514;
aStudent.rollNo = -514; //Error

1/25/16

COMSATS Intitute of Information Technology

216

Object and Class


Object is an instantiation of a user defined type or a
class

1/25/16

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;

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

219

Example
class Student{
int rollNo;
void setRollNo(int
aNo);
};
Student aStudent;
aStudent.rollNo;

1/25/16

Error

COMSATS Intitute of Information Technology

220

struct -> class transition!

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

Diff. between struct & class


struct TEST {
int x;
void Setx(int val) { x =
val; };
int Getx() { return x; };
}
main() {
TEST var;
var.x = 10; //possible
var.Setx(10);
int y = var.Getx();
}

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

By default struct (C++)} members are


National University of Computer and Emerging
public, whereas
class
members are private.
Sciences

222

Diff. between struct & class


struct TEST {
class TEST {
private:
int x;
int x;
public:
public:
void Setx(int val) { x =
void Setx(int val) { x =
val; };
val; };
int Getx() { return x; };
int Getx() { return x; };
}
}
main() {
main() {
TEST var;
TEST var;
var.x = 10; //error
var.x = 10; //error
var.Setx(10);
var.Setx(10);
int y = var.Getx();
int y = var.Getx();
}
By
default struct (C++)} members are
1/25/16

National University of Computer and Emerging


public, whereas
class
members are private.
Sciences

223

Access specifiers

1/25/16

COMSATS Intitute of Information Technology

224

Access specifiers
There are three access specifiers
public is used to tell that member can be accessed whenever
you have access to the object
private is used to tell that member can only be accessed
from a member function
protected to be discussed when we cover inheritance

1/25/16

COMSATS Intitute of Information Technology

225

Example
class Student{
private:
char * name;
int rollNo;
public:
void setName(char *);
void setRollNo(int);
...
};
1/25/16

Cannot be accessed outside class

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

227

Default access specifiers


When no access specifier is mentioned then by default
the member is considered private member

1/25/16

COMSATS Intitute of Information Technology

228

Example
class Student
{
char * name;

class Student

int RollNo;

private:

char * name;

};

int RollNo;
};

1/25/16

COMSATS Intitute of Information Technology

229

Example
class Student
{
char * name;
int RollNo;
void SetName(char *);
Error

};
Student aStudent;
aStudent.SetName(Ali);
1/25/16

COMSATS Intitute of Information Technology

230

Example
class Student
{
char * name;
int RollNo;
public:
void setName(char *);
};
Student aStudent;
aStudent.SetName(Ali);
1/25/16

COMSATS Intitute of Information Technology

231

Unified Modeling Language (UML) class


diagram
association
(using)

abstract

0..*

inheritance
(is a)

1/25/16

static

private

National University of Computer and Emerging


Sciences

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

COMSATS Intitute of Information Technology

233

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

4th ed. available in soft form.

Object Oriented Programming Using C++ by Joyce Farrell , published by


Course Technology, Cengage Learning. 4th ed. available in soft form

National University of Computer & Emerging Sciences


[www.nu.edu.pk]
Virtual University of Pakistan [ocw.vu.edu.pk]
Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
1/25/16

COMSATS Intitute of Information Technology

234

Thanks

1/25/16

COMSATS Intitute of Information Technology

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

Member Functions (contd.)


Define member function inside the class definition
OR
Define member function outside the class definition
But they must be declared inside class definition

Function Inside Class Body


class ClassName {

public:
ReturnType FunctionName() {

}
};

Example
Define a class of student
that has a roll number. This
class should have a
function that can be used
to set the roll number

Example
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){
rollNo = aRollNo;
}
};

Function Outside Class Body


class ClassName{

public:
ReturnType FunctionName();
};
ReturnType ClassName::FunctionName()
{

Scope
resolution
}
operator

Example
class Student{

int rollNo;
public:
void setRollNo(int aRollNo);
};
void Student::setRollNo(int aRollNo){

rollNo = aRollNo;
}

Inline Functions
Instead of calling an inline function compiler replaces
the code at the function call point
Keyword inline is used to request compiler to make a
function inline
It is a request and not a command

Example
inline int Area(int len, int hi)
{
return len * hi;
}
int main()
{
cout << Area(10,20);
}

Inline Functions
If we define the function inside the class body then the
function is by default an inline function
In case function is defined outside the class body then
we must use the keyword inline to make a function
inline

Example
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){

rollNo = aRollNo;
}
};

Example
class Student{

public:
inline void setRollNo(int aRollNo);
};
void Student::setRollNo(int aRollNo){

rollNo = aRollNo;
}

Example
class Student{

public:
void setRollNo(int aRollNo);
};
inline void Student::setRollNo(int aRollNo){

rollNo = aRollNo;
}

Example
class Student{

public:
inline void setRollNo(int aRollNo);
};
inline void Student::setRollNo(int aRollNo){

rollNo = aRollNo;
}

Constructor

Constructor
Constructor is used to initialize the objects of a class
Constructor is used to ensure that object is in well
defined state at the time of creation
Constructor is automatically called when the object is
created
Constructor are not usually called explicitly

Constructor (contd.)
Constructor is a special function having same name as
the class name
Constructor does not have return type
Constructors are commonly public members

Example
class Student{

public:
Student(){
rollNo = 0;

}
};

Example
int main()
{
Student aStudent;
/*constructor is implicitly called at this
point*/
}

Default Constructor
Constructor without any argument is called default
constructor
If we do not define a default constructor the compiler
will generate a default constructor
This compiler generated default constructor initialize
the data members to their default values

Example
class Student
{
int rollNo;
char *name;
float GPA;
public:

//no constructors
};

Example
Compiler generated default constructor
{
rollNo = 0;
GPA = 0.0;
name = NULL;
}

Constructor Overloading
Constructors can have parameters
These parameters are used to initialize the data
members with user supplied data

Example
class Student{

public:
Student();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(int aRollNo, int aRollNo, float aGPA);
};

Example
Student::Student(int aRollNo,
char * aName){
if(aRollNo < 0){
rollNo = 0;
}
else {
rollNo = aRollNo;
}

Example
int main()
{
Student student1;
Student student2(Name);
Student student3(Name, 1);
Student student4(Name,1,4.0);
}

Constructor Overloading
Use default parameter value to reduce the writing effort

Example
Student::Student( char * aName = NULL,
int aRollNo= 0,
float aGPA = 0.0){

}
Is equivalent to
Student();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(char * Name, int aRollNo, float aGPA);

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

4th ed. available in soft form.

Object Oriented Programming Using C++ by Joyce Farrell , published by


Course Technology, Cengage Learning. 4th ed. available in soft form

National University of Computer & Emerging Sciences


[www.nu.edu.pk]
Virtual University of Pakistan [ocw.vu.edu.pk]
Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
1/25/16

COMSATS Intitute of Information Technology

266

How to correctly Search for a


software @ google
When we need a software, the first place where we go
is at Google Search. If you don't know the software
name, then we use some keywords at Google Search
(for e.g. Note Taking software, Video Editing software,
Photo Editing software etc). Once Google show us the
results, we click the links after reading its title and
some description. Following such practice often
wastes our time by clicking useless links. What most
of the people don't know is that, you can easily search
for the software / applications at Google Search using
its filtering options. Let's see how we can do that
Consult the file uploaded

1/25/16

COMSATS Intitute of Information Technology

267

Thanks

1/25/16

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

270

Functions

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

1/25/16

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 functions code is stored in only one place in


Intitute of Information Technology
271
memory, evenCOMSATS
though
the function is executed

Return type

1/25/16

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

273

Functions

1/25/16

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.
COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

275

Inline Function

1/25/16

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.

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

277

Recursion

1/25/16

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 lets apply it to a program:
The next program, uses recursion instead of
a loop to calculate factorial.
COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

279

Recursion

1/25/16

COMSATS Intitute of Information Technology

280

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

1/25/16

4th ed. available in soft form.

COMSATS Intitute of Information Technology

281

Thanks

1/25/16

COMSATS Intitute of Information Technology

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);
}

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;
studentA
Name
RollNo
GPA

Memory
A
H
M
A
D

studentB
Name
RollNo
GPA

Assignment
Lab Assignment No 3

1/25/16

COMSATS Intitute of Information Technology

303

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

4th ed. available in soft form.

Object Oriented Programming Using C++ by Joyce Farrell , published by


Course Technology, Cengage Learning. 4th ed. available in soft form

National University of Computer & Emerging Sciences


[www.nu.edu.pk]
Virtual University of Pakistan [ocw.vu.edu.pk]
Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
1/25/16

COMSATS Intitute of Information Technology

304

Thanks

1/25/16

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

308

Using Destructor

1/25/16

// foo.cpp demonstrates destructor


#include <iostream>
using namespace std;
class Foo{
private:
int data;
public:
Foo() : data(0)
// constructor (same name as class)
{cout<< "Wakeup \n" ; }
~Foo()
// destructor (same name with tilde)
{cout<< "ByeBye \n" ; }
};
int main(){
Foo s1, s2;
// define two objects of class Foo
system( "PAUSE" ); // Foo *s3; s3 = new Foo; delete s3;
return 0;
}
COMSATS Intitute of Information Technology
309

this Pointer
There are situations where
designer wants to return
reference to current object
from a function
In such cases reference is
taken from this pointer like
(*this)

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;
}

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
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

Separation of interface and


implementation
Usually functions are defined in
implementation files (.cpp) while the
class definition is given in header file
(.h)
Some authors also consider this as
separation of interface and
implementation

Student.h
class Student{
int rollNo;
public:
void setRollNo(int aRollNo);
int getRollNo();

};

Student.cpp
#include student.h
void Student::setRollNo(int aNo){

}
int Student::getRollNo(){

Driver.cpp
#include student.h
int main(){
Student aStudent;
}

Classes, Objects and Memory

1/25/16

you might have the impression that each


object created from a class contains separate
copies of that classs data and member
functions.
Its 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 oncewhen they are defined
in the class definition.
Since the functions for each object are
identical. The
data
will
COMSATS
Intituteitems,
of Information however,
Technology
323 hold

1/25/16

COMSATS Intitute of Information Technology

324

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

4th ed. available in soft form.

Object Oriented Programming Using C++ by Joyce Farrell , published by


Course Technology, Cengage Learning. 4th ed. available in soft form

National University of Computer & Emerging Sciences


[www.nu.edu.pk]
Virtual University of Pakistan [ocw.vu.edu.pk]
Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
1/25/16

COMSATS Intitute of Information Technology

325

Thanks

1/25/16

COMSATS Intitute of Information Technology

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!

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?
1/25/16

COMSATS Intitute of Information Technology

328

static class member data


class foo {
private:
static int count; //note: declaration only!
public:
foo() //incr count when object created
{ count++;
}
int getcount() //returns count

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

COMSATS Intitute of Information Technology


int foo::count = 0; //*definition*
of count

329

static class member


For multiple objects of the same class, new
memory is allocated for data members and
shared memory for all the functions.
This shared memory is also used for static
data members.
Static data member requires two separate
statements for:
Declaration (compiler is told about type and
name)
Definition (compiler sets aside memory)
1/25/16

COMSATS Intitute of Information Technology

330

static class member


Why this two-part approach?
If static member data were defined inside the class (as it
actually was in early versions of C++), it would violate the
idea that a class definition is only a blueprint and does not
set aside any memory.
Putting the definition of static member data outside the
class also serves to emphasize that the memory space for
such data is allocated only once, before the program starts
to execute,
and that one static member variable is accessed by an
entire class; each object does not have its own version of
the variable, as it would with ordinary member data.
In this way a static member variable is more like a global
variable.
1/25/16

COMSATS Intitute of Information Technology

331

static class member


Be careful:
Its 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 youre 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).
1/25/16

COMSATS Intitute of Information Technology

332

Variable packing in memory


If you do a sizeof(class_obj_or_name) for an
object of a class/struct or class/struct name,
you get the size of the memory allocated for
data members.
Memory alignment in class/struct is a bit
different.

1/25/16

COMSATS Intitute of Information Technology

333

Data member packing in


class/struct
class Counter

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;

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.

static int obj;


public:
Counter() : count(0)
{
1/25/16

COMSATS Intitute of Information Technology

334

const Member Functions

There are functions that are meant


to be read only
There must exist a mechanism to
detect error if such functions
accidentally change the data
member
1/25/16

COMSATS Intitute of Information Technology

335

Example
bool Student::isRollNo(int aNo){
if(rollNo = = aNo){
return true;
}
return false;
}

1/25/16

COMSATS Intitute of Information Technology

336

Example
bool Student::isRollNo(int aNo){
/*undetected typing mistake*/
if(rollNo = aNo){
return true;
}
return false;
}
1/25/16

COMSATS Intitute of Information Technology

337

Example
bool Student::isRollNo
(int aNo)const{
/*compiler error*/
if(rollNo = aNo){
return true;
}
return false;
}
1/25/16

COMSATS Intitute of Information Technology

338

const Member Functions

Keyword const is placed at the end


of the parameter list

1/25/16

COMSATS Intitute of Information Technology

339

const Member Functions


Declaration:
class ClassName{
ReturnVal Function() const;
};
Definition:
ReturnVal ClassName::Function() const{

}
1/25/16

COMSATS Intitute of Information Technology

340

Example
class Student{
public:
int getRollNo() const {
return rollNo;
}
};

1/25/16

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

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

343

Example
class Time{
public:
Time() const {}
~Time() const {}
};

1/25/16

//error
//error

COMSATS Intitute of Information Technology

344

const Function
Constant member function cannot
change data member
Constant member function cannot
access non-constant member
functions
1/25/16

COMSATS Intitute of Information Technology

345

Example
class Student{
char * name;
public:
char *getName();
void setName(char * aName);
int ConstFunc() const{
name = getName();//error
setName(Ahmad);//error
}
};
1/25/16

COMSATS Intitute of Information Technology

346

1/25/16

COMSATS Intitute of Information Technology

347

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

4th ed. available in soft form.

Object Oriented Programming Using C++ by Joyce Farrell , published by


Course Technology, Cengage Learning. 4th ed. available in soft form

National University of Computer & Emerging Sciences


[www.nu.edu.pk]
Virtual University of Pakistan [ocw.vu.edu.pk]
Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
1/25/16

COMSATS Intitute of Information Technology

348

Thanks

1/25/16

COMSATS Intitute of Information Technology

349

CSC241:
Object Oriented
Programming
Spring 2013
1.Arrays & String (Chapter 7)
1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!

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 arrays elements as
type double
cout << "Enter " << SIZE << " numbers:\t";
for (int i=0; i<SIZE; i++)
cin >> a[i];
cout << "In reverse order: ";
for (int i=SIZE-1; i>=0; i--)
cout << " " << a[i];
system("PAUSE"); return 0;
}

Out of Bounds
#include <iostream>
using namespace std;
int main(){
float a[] = { 22.2,44.4, 66.6 };
float x=11.1;
cout << "I m going to Crash " << endl;
cin >> x;
a[3333] = 88.8; // ERROR: index is out of bounds!
return 0;
}

Passing Array to Function


#include <iostream>
using namespace std;
int sum(int[],int); // declaration
int main(){
int a[] = { 11,33, 55,77 };
int size = sizeof(a)/sizeof(int);
cout << "sum(a,size) = " << sum(a,size) << endl;
cout << endl << a[0] << endl;
system("PAUSE"); return 0;
}
int sum(int a[],int n){
int sum=0;
for (int i=0; i<n; i++)
sum += a[i];
a[0] = 100;
return sum;
}

n Dimensional Arrays
#include <iostream>
using namespace std;
int main(){ const int row=2, col=3; int i,j;
int ary[row][col] = {
{11,12,13},
{21,22,23}
};
for(i=0 ; i< row ; i++){
for(j=0 ; j<col; j++){ cout << ary[i][j] << " ";}
cout << endl;
}
for(i=0 ; i< row ; i++){
for(j=0 ; j<col; j++){
cout << &ary[i][j] << "="<<ary[i][j]<<"\t";}
cout << endl;}
return 0;
}

n Dimensional Arrays

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

Calculating Square of a Matrix


#include <iostream>
using namespace std;
int main(){ const int row=3, col=3; int i,j;
int A[row][col];
cout << "Square of a " <<row
<<"x"<<col<<"Matrices"<<endl;
for(i=0 ; i< row ; i++){
for(j=0 ; j<col; j++){
cout << "A[" << i+1 << "][" << j+1 << "]= ";
cin >> A[i][j];
}
}
for(i=0 ; i< row ; i++)
for(j=0 ; j<col; j++)
A[i][j] = A[i][j]*A[i][j];
for(i=0 ; i< row ; i++){
for(j=0 ; j<col; j++)
cout << A[i][j] << "\t";
cout << endl;
}
return 0;
}

Passing 2D Array to Function


#include <iostream>
using namespace std;
void get_data(float a[][3],int row, int col){
int i,j;
for (i=0; i<row; i++)
for (j=0; j<col; j++){
cout << "A["<<i+1<<"]["<<j+1<<"]:";
cin >> a[i][j];}
}
void show_data(float a[][3],int row, int col){
int i,j;
for (i=0; i<row; i++){
for (j=0; j<col; j++)
{cout << a[i][j] << "\t";}
cout << endl; }
}
int main(){
float matrix[4][3]; // 4 rows and 3 columns
get_data(matrix,4,3);
show_data(matrix,4,3);
return 0;
}

Passing 3D Array to Function (1/2)


#include <iostream>
using namespace std;
void get_data(float a[][3][2],int row, int col,int page){
int i,j,k;
for (k=0; k<page; k++){
for (i=0; i<row; i++){
for (j=0; j<col; j++){
cout <<"A["<< i <<"]["<< j <<"]["<< k <<"]:";
cin >> a[i][j][k];
} // end of for (j=0
} // end of for (i=0
} // end of for (k=0
}

Passing 3D Array to Function (2/2)


void show_data(float a[][3][2],int row, int col, int page){
int i,j,k;
for (k=0; k<page; k++){
for (i=0; i<row; i++){
for (j=0; j<col; j++){
cout << a[i][j][k] << "\t";
}
cout << endl;
}
cout << endl;
}
}
int main(){
float matrix[4][3][2]; // 4 rows, 3 columns, 2 pages
get_data(matrix,4,3,2);
show_data(matrix,4,3,2);
system("PAUSE");
return 0;
}

Sorting Data Using Bubble Sort Algo


#include <iostream>
using namespace std;
void print( float[], int );
void sort ( float[], int );
int main(){
int i; float data[10];
cout << "Enter 10 Numbers for Sorting \n";
for( i=0 ; i<10 ; i++ ){
cout << "Enter No." <<i+1<< ":" ;
cin >> data[i];
}
sort(data,10);
print(data,10);
return 0;
}

Sorting Data Using Bubble Sort Algo


void sort( float a[], int n ){ // bubble sort:
for (int i=1; i<n; i++) // bubble up max{a[0..n-i]}:
for (int j=0; j<n-i; j++)
if (a[j] > a[j+1]){
float temp = a[j];
a[j]=a[j+1];
a[j+1] = temp;
}
}
void print( float a[], int n ){
cout << " Sorted Data is " << endl;
for (int i=0; i<n; i++)
cout << a[i] <<" ";
}

Using C-string
#include <iostream>
#include <iomanip.h>
using namespace std;
int main(){
char str[] = { 'M','.',' ','A','l','i',0,' ',
'I','I','U',0}; // char ch [] = "M. Ali";
int size = sizeof(str);
cout << "\n The Character Array Size is :" <<size
<< " Bytes" << endl;
for ( int i=0 ; i<size ; i++ )
cout << "str[" << i << "]=" <<str[i] <<" =["
<< int(str[i]) << "]" << endl;
cout << endl << str << endl;
system("PAUSE");
return 0;
}

Reading Embedded Blanks


// blanksin.cpp reads string with embedded blanks
#include <iostream>
using namespace std;
int main(){
const int MAX = 80;
// max characters in string
char str[MAX];
// string variable str
cout << "\nEnter a string: ";
// cin.get() means a member function get() of the stream
// class of which cin is an object
cin.get(str, MAX); // put string in str
// first argument to get() is the array address where
the
// string being input will be placed.
// The second argument specifies the maximum size of the
// array
cout << "You entered: " << str << endl;
return 0;
}

Copying a String the Hard Way


// strcopy1.cpp
// copies a string using a for loop
#include <iostream>
#include <cstring> //for strlen()
using namespace std;
int main(){ //initialized string
char str1[] =
"Oh, Captain, my Captain! "
"our fearful trip is done";
const int MAX = 80; int j; // MAX is size of str2 buffer
char str2[MAX]; //empty string
for( j=0; j<strlen(str1); j++) //copy strlen characters
str2[j] = str1[j]; // from str1 to str2
str2[j] = '\0'; //insert NULL at end
cout << str2 << endl; //display str2
system("PAUSE"); return 0;
}

Copying a String the Easy Way


// strcopy2.cpp
// copies a string using strcpy() function
#include <iostream>
#include <cstring> //for strcpy()
using namespace std;
int main(){
char str1[] = "Tiger, tiger, burning 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 array
const int MAX = 10; //maximum size of each string
//An array of strings
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday" , "Saturday" };
for( int j=0 ; j<DAYS ; j++) //display every string
cout << star[j] << endl;
system("PAUSE");
return 0;
}

Array of Strings

Lab Task
Write a and test a program to calculate Determinant and Reverse of a 3x3 matrix

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

4th ed. available in soft form.

Object Oriented Programming Using C++ by Joyce Farrell , published by


Course Technology, Cengage Learning. 4th ed. available in soft form

National University of Computer & Emerging Sciences


[www.nu.edu.pk]
Virtual University of Pakistan [ocw.vu.edu.pk]
Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
1/25/16

COMSATS Intitute of Information Technology

376

Thanks

1/25/16

COMSATS Intitute of Information Technology

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;
}

Allocation with new Operator


new operator can be used to create objects at runtime

Example
int main(){
Student *ptr;
ptr = new Student;
ptr->setRollNo(10);
return 0;
}

Example
int main(){
Student *ptr;
ptr = new Student(Ali);
ptr->setRollNo(10);
return 0;
}

Breakup of new Operation


new operator is decomposed as follows
Allocating space in memory
Calling the appropriate constructor

Case Study
Design a class date through which user must be able to
perform following operations
Get and set current day, month and year
Increment by x number of days, months and year
Set default date

Attributes
Attributes that can be seen in this problem statement
are

Day
Month
Year
Default date

Attributes
The default date is a feature shared by all objects
This attribute must be declared a static member

Attributes in Date.h
class Date
{
int day;
int month;
int year;
static Date defaultDate;

};

Interfaces
getDay
getMonth
getYear
setDay
setMonth
setYear

addDay

addMonth

addYear

setDefaultDate

Interfaces
As the default date is a static member the interface
setDefaultDate should also be declared static

Interfaces in Date.h
class Date{

public:
void setDay(int aDay);
int getDay() const;
void addDay(int x);

};

Interfaces in Date.h
class Date{

public:
static void setDefaultDate(
int aDay,int aMonth, int aYear);

};

Constructors and Destructors in Date.h


Date(int aDay = 0,
int aMonth= 0, int aYear= 0);
~Date(); //Destructor
};

Implementation of Date Class


The static member variables must be initialized
Date Date::defaultDate (07,3,2013);

Constructors
Date::Date(int aDay, int aMonth,
int aYear) {
if(aDay==0) {
this->day = defaultDate.day;
}
else{
setDay(aDay);
}
//similarly for other members
}

Destructor
We are not required to do any house keeping chores in
destructor
Date::~Date
{
}

Getter and Setter


void Date::setMonth(int a){
if(a > 0 && a <= 12){
month = a;
}
int getMonth() const{
return month;
}

addYear
void Date::addYear(int x){
year += x;
if(day == 29 && month == 2
&& !leapyear(year)){
day = 1;
month = 3;
}
}

Helper Function
class Date{

private:
bool leapYear(int x) const;

};

Helper Function
bool Date::leapYear(int x) const{
if((x%4 == 0 && x%100 != 0)
|| (x%400==0)){
return true;
}
return false;
}

setDefaultDate
void Date::setDefaultDate(
int d, int m, int y){
if(d >= 0 && d <= 31){
day = d;
}

Aggregation
Composition vs.
Aggregation

Aggregation is a weak relationship


Room
area : float
chairs[50]:Chair *
Room(char *, int)
~Room()
FoldChair(int) : bool

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

The sub-object has a life that is


dependant on the life of its master class

e.g:
Chairs can be moved inside or outside at
anytime
When Room is destroyed, the chairs may
or may not be destroyed

Aggregation
class Room{
private:
float area;
Chair * chairs[50];
Public:
Room();
void AddChair(Chair *, int chairNo);
Chair * GetChair(int chairNo);
bool FoldChair(int chairNo);

};

Aggregation
Room::Room(){
for(int i = 0; i < 50; i++)

chairs[i] = NULL;
}
void Room::AddChair(Chair *
chair1, int chairNo){
if(chairNo >= 0 && chairNo < 50)
chairs[chairNo] = chair1;
}

Aggregation
Chair * Room::GetChair(int chairNo){
if(chairNo >= 0 && chairNo < 50)
return chairs[chairNo];
else
return NULL;
}
bool Room::FoldChair(int chairNo){
if(chairNo >= 0 && chairNo < 50)
return chairs[chairNo]->FoldChair();
else
return false;
}

Aggregation
int main(){
Chair ch1;
{
Room r1;
r1.AddChair(&ch1, 1);
r1.FoldChair(1);
}
ch1.UnFoldChair(1);
return 0;
}

Friend
Functions

Consider the following class:


class X{
private:
int a, b;
public:
void MemberFunction();

Friend
Functions

Global function:
void DoSomething(X obj){
obj.a = 3; //Error
obj.b = 4; //Error
}

Friend
Functions

In order to access the member variables of the


class, function definition must be made a friend
function:
class X{
private:
int a, b;
public:

friend void DoSomething(X obj);


}
Now the function DoSomething can access data
members of class X

Friend
Functions
Prototypes of friend
functions appear in the
class definition
But friend functions are
NOT member functions

Friend
Functions

Friend functions can be placed anywhere


in the class without any effect
Access specifiers dont 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, 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;

};

Member functions of class Y can


access private data members of class
X

Friend Classes
Example:
class X{
friend class Y;
private:
int x_var1, x_var2;
...
};

Friend Classes
class Y{
private:
int y_var1, y_var2;
X objX;
public:
void setX(){
objX.x_var1 = 1;
}
};

Friend Classes
int main(){
Y objY;
objY.setX();
return 0;
}

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

4th ed. available in soft form.

Object Oriented Programming Using C++ by Joyce Farrell , published by


Course Technology, Cengage Learning. 4th ed. available in soft form

National University of Computer & Emerging Sciences


[www.nu.edu.pk]
Virtual University of Pakistan [ocw.vu.edu.pk]
Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
1/25/16

COMSATS Intitute of Information Technology

420

Thanks

1/25/16

COMSATS Intitute of Information Technology

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

Complex Add(const Complex &);


Complex Subtract(const Complex &);
Complex Multiply(const Complex &);

COMSATS Intitute of
Information Technology

class Complex{
private:
double real, img;
public:

1/25/16

Consider the following class:

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

The following statement:

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

Alternative way is:


t1 = c3.Add(c4);
t2 = c2.Add(t1);
t3 = c1.Add(t2);

1/25/16

Operator overloading

427

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

COMSATS Intitute of
Information Technology

If the mathematical expression is big:

1/25/16

Operator overloading

428

COMSATS Intitute of
Information Technology

C++ provides a very elegant solution:


Operator overloading
C++ allows you to overload common
operators like +, - or * etc
Mathematical statements dont have to be
explicitly converted into function calls

1/25/16

Operator overloading

429

COMSATS Intitute of
Information Technology

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

1/25/16

Operator overloading

430

COMSATS Intitute of
Information Technology

C++ automatically overloads


operators for pre-defined types
Example of predefined types:
int
float
double
char
long

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

// for float addition:


Add(float a, float b)

COMSATS Intitute of
Information Technology

The compiler probably calls the


correct overloaded low level function
for addition i.e:
// for integer addition:
Add(int a, int b)

1/25/16

Operator overloading

433

COMSATS Intitute of
Information Technology

Operator functions are not usually


called directly
They are automatically invoked to
evaluate the operations they
implement

1/25/16

Operator overloading

434

COMSATS Intitute of
Information Technology

List of operators that can be


overloaded in C++:

1/25/16

Operator overloading

435

Reason: They take name,


rather than value in their
argument except for ?:
?: is the only ternary operator
in C++ and cant be overloaded

COMSATS Intitute of
Information Technology

List of operators that cant be


overloaded:

1/25/16

Operator overloading

436

COMSATS Intitute of
Information Technology

The precedence of an operator is


NOT affected due to overloading
Example:
c1*c2+c3
c3+c2*c1
both yield the same answer

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

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

1/25/16

Operator overloading

439

COMSATS Intitute of
Information Technology

Always write code


representing the operator
Example:
Adding subtraction code
inside the + operator
will create chaos

1/25/16

Operator overloading

440

COMSATS Intitute of
Information Technology

Creating a new operator is


a syntax error (whether
unary, binary or ternary)
You cannot create $

1/25/16

Operator overloading

441

COMSATS Intitute of
Information Technology

Arity of an operator is NOT affected


by overloading
Example:
Division operator will take
exactly two operands in any
case:
b = c / d

1/25/16

Operator overloading

442

COMSATS Intitute of
Information Technology

Binary operators act on two


quantities
Binary operators:

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

The operator OP must have at


least one formal parameter of type
class (user defined type)
Following is an error:
int operator + (int, int);

446

COMSATS Intitute of
Information Technology

Overloading + operator:
class Complex{
private:
double real, img;
public:

Complex operator +(const


Complex & rhs);
};

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

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);

1/25/16

Binary operators

449

COMSATS Intitute of
Information Technology

If the return type was void,


class Complex{
...
public:
void operator+(

const Complex & rhs);


};

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

we have to do the same operation


c1+c2+c3 as:
c1+c2
c1+c3
// final result is stored in c1

1/25/16

Binary operators

452

Assignments and cascaded expressions are not


possible
Code is less readable
Debugging is tough
Code is very hard to maintain

COMSATS Intitute of
Information Technology

Drawback of void return type:

1/25/16

Binary operators

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]
1/25/16

COMSATS Intitute of Information Technology

454

Thanks

1/25/16

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

457

UML Notation

1/25/16

Parent Class

Base Class

Child Class

Derived Class

COMSATS Intitute of Information Technology

458

Inheritance in C++
There are three types of inheritance in C++
Public
Private
Protected

1/25/16

COMSATS Intitute of Information Technology

459

IS A Relationship
IS A relationship is modeled with the help
of public inheritance
Syntax
class ChildClass
: public BaseClass{
...
};

1/25/16

COMSATS Intitute of Information Technology

460

Example
class Person{
...
};
class Student: public Person{
...
};

1/25/16

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)

1/25/16

COMSATS Intitute of Information Technology

462

Example
class Person{
char *name;
int age;
...
public:
const char *GetName() const;
int GetAge() const;
...
};

1/25/16

COMSATS Intitute of Information Technology

463

Example
class Student: public Person{
int semester;
int rollNo;
...
public:
int GetSemester() const;
int GetRollNo() const;
void Print() const;
...
};
1/25/16

COMSATS Intitute of Information Technology

464

Example
void Student::Print()
{

ERROR
cout << name << is in << semester
<< semester;

1/25/16

COMSATS Intitute of Information Technology

465

Example
void Student::Print()
{
cout << GetName()
<< is in semester
semester;

<<

1/25/16

COMSATS Intitute of Information Technology

466

Example
int main(){
Student stdt;
stdt.semester = 0;//error
stdt.name = NULL; //error
cout << stdt.GetSemester();
cout << stdt.GetName();
return 0;
}

1/25/16

COMSATS Intitute of Information Technology

467

Allocation in Memory
The object of derived class is represented
in memory as follows

base member1
base member2
...

Data members of
base class

derived member1 Data members of


derived member2
derived class
...
1/25/16

COMSATS Intitute of Information Technology

468

Allocation in Memory
Every object of derived class has an
anonymous object of base class

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

470

Constructors
base member1
base member2
...

Base class constructor


initializes the
anonymous object

derived member1
derived member2
...

Derived class
constructor initializes
the derived class
object

1/25/16

COMSATS Intitute of Information Technology

471

Example
class Parent{
public:
Parent(){ cout <<
Parent Constructor...;}
};
class Child : public Parent{
public:
Child(){ cout <<
Child Constructor...;}
};
1/25/16

COMSATS Intitute of Information Technology

472

Example
int main(){
Child cobj;
return 0;
}

Output:
Parent Constructor...
Child Constructor...
1/25/16

COMSATS Intitute of Information Technology

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

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

1/25/16

COMSATS Intitute of Information Technology

475

Example
class Parent{
public:
Parent(int i){}
};
class Child : public Parent{
public:
Child(){}
} Child_Object; //ERROR

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

477

Example
class Parent{
public:
Parent(int i){};
};
class Child : public Parent{
public:
Child(int i): Parent(i)
{}
};

1/25/16

COMSATS Intitute of Information Technology

478

Example
class Parent{
public:
Parent(){cout <<
Parent Constructor...;}
...
};
class Child : public Parent{
public:
Child():Parent()
{cout << Child Constructor...;}
...
};

1/25/16

COMSATS Intitute of Information Technology

479

Base Class Initializer


User can provide base class initializer
and member initializer simultaneously

1/25/16

COMSATS Intitute of Information Technology

480

Example
class Parent{
public:
Parent(){}
};
class Child : public Parent{
int member;
public:
Child():member(0), Parent()
{}
};
1/25/16

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.

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

483

Example
class Person{
public:
int age;
char *name;
...
public:
Person();
};

1/25/16

COMSATS Intitute of Information Technology

484

Example
class Student: public Person{
private:
int semester;
...
public:
Student(int a):age(a)
{
//error
}
};

1/25/16

COMSATS Intitute of Information Technology

485

Reason
It will be an assignment not an initialization

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

487

Example
class Parent{
public:
Parent(){cout <<Parent Constructor;}
~Parent(){cout<<Parent Destructor;}
};
class Child : public Parent{
public:
Child(){cout << Child Constructor;}
~Child(){cout << Child Destructo;}
};

1/25/16

COMSATS Intitute of Information Technology

488

Example
Output:
Parent Constructor
Child Constructor
Child Destructor
Parent Destructor

1/25/16

COMSATS Intitute of Information Technology

489

Protected Access Specifier

1/25/16

COMSATS Intitute of Information Technology

490

Date Class

class Date{
int day, month, year;
static Date defaultDate;
public:
void SetDay(int aDay);
int GetDay() const;
void AddDay(int x);

static void SetDefaultDate(


int aDay,int aMonth, int aYear);

Date Class
...
private:
bool IsLeapYear();
};
int main(){
Date aDate;
aDate.IsLeapYear(); //Error
return 0;
}

Creating SpecialDate Class


Date

Special Date

Special Date

AddSpecialYear
...

Creating SpecialDate Class


class SpecialDate: public Date{

public:
void AddSpecialYear(int i){
...
if(day == 29 && month == 2
&& !IsLeapyear(year+i)){ //ERROR!
...
}
}
};

Modify Access Specifier


We can modify access specifier IsLeapYear from
private to public

Modified Date Class


class Date{
public:
...
bool IsLeapYear();
};

Modified AddSpecialYear
void SpecialDate :: AddSpecialYear
(int i){
...
if(day == 29 && month == 2
&& !IsLeapyear(year+i)){
...
}
}

Protected members
Protected members can not be accessed outside the
class
Protected members of base class become protected
member of derived class in Public inheritance

Modified Date Class


class Date{

protected:
bool IsLeapYear();
};
int main(){
Date aDate;
aDate.IsLeapYear(); //Error
return 0;
}

Modified AddSpecialYear
void SpecialDate :: AddSpecialYear
(int i){
...
if(day == 29 && month == 2
&& !IsLeapyear(year+i)){
...
}
}

Disadvantages
Breaks encapsulation
The protected member is part of base classs
implementation as well as derived classs
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]
1/25/16

COMSATS Intitute of Information Technology

502

Thanks

1/25/16

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

505

Example
GrandParent

1/25/16

Parent1

Parent2

Child1

Child2

COMSATS Intitute of Information Technology

506

Direct Base Class


A direct base class is explicitly
listed in a derived class's header
with a colon (:)

class Child1:public Parent1


...
1/25/16

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

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

COMSATS Intitute of Information Technology

509

Example
class GrandParent{
int gpData;
public:
GrandParent() : gpData(0){...}
GrandParent(int i) : gpData(i){...}
void Print() const;
};
1/25/16

COMSATS Intitute of Information Technology

510

Example
class Parent1: public GrandParent{
int pData;
public:
Parent1() : GrandParent(),

pData(0) {}

};

1/25/16

COMSATS Intitute of Information Technology

511

Example
class Child1 : public Parent1 {
public:
Child1() : Parent1() {...}
Child1(int i) : GrandParent (i) //Error
{...}
void Print() const;
};

1/25/16

COMSATS Intitute of Information Technology

512

Overriding
Child class can override the function of GrandParent
class

1/25/16

COMSATS Intitute of Information Technology

513

Example
GrandParent
Print()
Parent1
Child1
Print()
1/25/16

COMSATS Intitute of Information Technology

514

Example
void GrandParent::Print() {
cout << GrandParent::Print
<< endl;
}
void Child1::Print() {
cout << Child1::Print << endl;
}
1/25/16

COMSATS Intitute of Information Technology

515

Example
int main(){
Child1 obj;
obj.Print();
obj.Parent1::Print();
obj.GrandParent::Print();
return 0;
}
1/25/16

COMSATS Intitute of Information Technology

516

Output
Output is as follows
Child1::Print
GrandParent::Print
GrandParent::Print

1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

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

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

1/25/16

COMSATS Intitute of Information Technology

523

Example
class Collection {
...
public:
void AddElement(int);
bool SearchElement(int);
bool SearchElementAgain(int);
bool DeleteElement(int);
};
1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

525

Class Set
class Set: private Collection {
private:
...
public:
void AddMember(int);
bool IsMember(int);
bool DeleteMember(int);
};
1/25/16

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);
}
1/25/16

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]
1/25/16

COMSATS Intitute of Information Technology

528

Thanks

1/25/16

COMSATS Intitute of Information Technology

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

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

1/25/16

COMSATS Intitute of Information Technology

Example
class Collection {
...
public:
void AddElement(int);
bool SearchElement(int);
bool SearchElementAgain(int);
bool DeleteElement(int);
};
1/25/16

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

1/25/16

COMSATS Intitute of Information Technology

Class Set
class Set: private Collection {
private:
...
public:
void AddMember(int);
bool IsMember(int);
bool DeleteMember(int);
};
1/25/16

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);
}
1/25/16

COMSATS Intitute of Information Technology

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

COMSATS Intitute of Information Technology

Specialization (Restriction)
Specialization (Restriction) can be implemented using
private and protected inheritance

1/25/16

COMSATS Intitute of Information Technology

age = a

setAge( a )

Adult
age : [18..125]
setAge( a )

If age < 18 then


error
else
age = a

COMSATS Intitute of
Information Technology

Person
age : [0..125]

1/25/16

Example Specialization (Restriction)

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

class Adult : private Person {


public:
bool SetAge(int _age){
if (_age >=18 && _age <= 125) {
age = _age;
return true;
}
return false;
}
};
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 lets 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.
Weve 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 widgetstamping 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 employees 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
1/25/16

COMSATS Intitute of Information Technology

1/25/16

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().
1/25/16

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.
1/25/16

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.
1/25/16

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]
1/25/16

COMSATS Intitute of Information Technology

Thanks

1/25/16

COMSATS Intitute of Information Technology

CSC241:
Object Oriented
Programming
Spring 2013
1.
2.
3.
4.

Overriding & Overloading


Multiple Inheritance
Virtual Inheritance
Virtual Functions/Members

1/25/16
Farhan Aadil
Please turn OFF your Mobile Phones!

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

1/25/16

COMSATS Institute of Information Technology

553

Overriding
Parent
...
Func1
Child
...
Func1
1/25/16

COMSATS Institute of Information Technology

554

Overriding
class Parent {
public:
void Func1();
void Func1(int);
};
class Child: public Parent {
public:
void Func1();
};
1/25/16

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

1/25/16

COMSATS Institute of Information Technology

556

Overriding
class Parent {
public:
void Func1();
void Func1();

//Error

};

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

558

Example
class Person{
public:
void Walk();
};
class ParalyzedPerson: public Person{
public:
void Walk();
};
1/25/16

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

1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

562

Example
int main(){
Student a(Ahmad, Computer
Science);
a.Print();
return 0;
}

1/25/16

COMSATS Institute of Information Technology

563

Output
Output:
Name: Ahmed
Major: Computer Science

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

565

Example
class Student : public Person{
char * major;
public:
Student(char * aName, char* m);

void Print(){
Print();//Print of Person
cout<<Major: << major <<endl;
}
...
};
1/25/16

COMSATS Institute of Information Technology

566

Example
int main(){
Student a(Ahmad, Computer
Science);
a.Print();
return 0;
}

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

568

Example
class Student : public Person{
char * major;
public:
Student(char * aName, char* m);
void Print(){
Person::Print();
cout<<Major: << major <<endl;
}
...
};
1/25/16

COMSATS Institute of Information Technology

569

Example
int main(){
Student a(Ahmad, Computer
Science);
a.Print();
return 0;
}

1/25/16

COMSATS Institute of Information Technology

570

Output
Output:
Name: Ahmed
Major: Computer Science

1/25/16

COMSATS Institute of Information Technology

571

{Before New Topic}

I need Your anonymous

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

COMSATS Institute of Information Technology

573

Multiple Inheritance
Transmitter
...
Transmit()

Receiver
...
Receive()

Phone
1/25/16

COMSATS Institute of Information Technology

574

Example
class Phone: public Transmitter,

public Receiver

{
...
};

1/25/16

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

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

577

Example
int main(){
Phone obj;
obj.Transmit();
obj.Receive();
return 0;
}

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

579

Example
int main(){
Phone obj;
Transmitter * tPtr = &obj;
Receiver * rPtr = &obj;
return 0;
}

1/25/16

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

1/25/16

COMSATS Institute of Information Technology

581

Example
int main(){
Phone obj;
Transmitter * tPtr = &obj;
tPtr->Transmit();
tPtr->Receive();

//Error

return 0;
}
1/25/16

COMSATS Institute of Information Technology

582

Example
int main(){
Phone obj;
Receiver * rPtr = &obj;
rPtr->Receive();
rPtr->Transmit(); //Error
return 0;
}
1/25/16

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

1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

586

Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
};
int main(){
AmphibiousVehicle obj;
obj.GetMaxLoad(); // Error
return 0;
}
1/25/16

COMSATS Institute of Information Technology

587

Multiple Inheritance
Programmer must explicitly specify the class name
when calling ambiguous function

1/25/16

COMSATS Institute of Information Technology

588

Example
int main(){
AmphibiousVehicle obj;
obj.LandVehicle::GetMaxLoad();
obj.WaterVehicle::GetMaxLoad();
return 0;
}

1/25/16

COMSATS Institute of Information Technology

589

Multiple Inheritance
The ambiguous call problem can arise when dealing
with multiple level of multiple inheritance

1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

592

Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
};
int main(){
AmphibiousVehicle obj;
obj.GetMaxLoad(); // Error
return 0;
}
1/25/16

COMSATS Institute of Information Technology

593

Example
int main()
{
AmphibiousVehicle obj;
obj.Vehicle::GetMaxLoad(); //Error
return 0;
}
Vehicle is accessible through two paths
1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

596

Multiple Inheritance
Data member must be used with care when dealing with
more then one level on inheritance

1/25/16

COMSATS Institute of Information Technology

597

Example
class Vehicle{
protected:
int weight;
};
class LandVehicle : public Vehicle{
};
class WaterVehicle : public Vehicle{
};
1/25/16

COMSATS Institute of Information Technology

598

Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
public:
AmphibiousVehicle(){
LandVehicle::weight = 10;
WaterVehicle::weight = 10;
}
};
There are multiple copies of data member weight
1/25/16

COMSATS Institute of Information Technology

599

COMSATS Institute of
Information Technology

Data Members Data Members


of Vehicle
of Vehicle
Data Members
Data Members
of
of LandVehicle
WaterVehicle
Data Members of
AmphibiousVehicle

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

COMSATS Institute of Information Technology

601

Example
class Vehicle{
protected:
int weight;
};
class LandVehicle :
public virtual Vehicle{
};
class WaterVehicle :
public virtual Vehicle{
};
1/25/16

COMSATS Institute of Information Technology

602

Example
class AmphibiousVehicle:
public LandVehicle,
public WaterVehicle{
public:
AmphibiousVehicle(){
weight = 10;
}
};
1/25/16

COMSATS Institute of Information Technology

603

Memory View
Data Members of Vehicle
Data Members
Data Members
of
of LandVehicle
WaterVehicle
Data Members of
AmphibiousVehicle
1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

605

Example
Student
GPA

BS Student MS Student PhD Student

MS/PhD Student
1/25/16

COMSATS Institute of Information Technology

606

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]
1/25/16

COMSATS Institute of Information Technology

607

Thanks

1/25/16

COMSATS Institute of Information Technology

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

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??
1/25/16

COMSATS Institute of Information Technology

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

COMSATS Institute of Information Technology

612

Motivation
Following function prints an array of integer elements:
void printArray(int* array, int size)
{
for ( int i = 0; i < size; i++ )
cout << array[ i ] << , ;
}

...Motivation
What if we want to print an array of characters?
void printArray(char* array,
int size)
{
for ( int i = 0; i < size; i++ )
cout << array[ i ] << , ;
}

...Motivation
What if we want to print an array of doubles?
void printArray(double* array,
int size)
{
for ( int i = 0; i < size; i++ )
cout << array[ i ] << , ;
}

...Motivation
Now if we want to change the way function prints the
array. e.g. from
1, 2, 3, 4, 5
to
1-2-3-4-5

...Motivation
Now consider the Array class that wraps an array of
integers
class Array {
int* pArray;
int size;
public:

};

...Motivation
What if we want to use an Array class that wraps arrays
of double?
class Array {
double* pArray;
int size;
public:

};

...Motivation
What if we want to use an Array class that wraps arrays
of boolean variables?
class Array {
bool* pArray;
int size;
public:

};

...Motivation
Now if we want to add a function sum to Array class,
we have to change all the three classes

Generic Programming
Generic programming refers to programs containing
generic abstractions
A generic program abstraction (function, class) can be
parameterized with a type
Such abstractions can work with many different types of
data

Advantages
Reusability
Writability
Maintainability

Templates
In C++ generic programming is done using templates
Two kinds
Function Templates
Class Templates

Compiler generates different type-specific copies from a


single template

Function Templates
A function template can be parameterized to operate on
different types of data

Declaration
template< class T >
void funName( T x );
// OR
template< typename T >
void funName( T x );
// OR
template< class T, class U, >
void funName( T x, U y, );

Example Function Templates


Following function template prints an array having almost
any type of elements:
template< typename T >
void printArray( T* array, int size )
{
for ( int i = 0; i < size; i++ )
cout << array[ i ] << , ;
}

Example Function Templates


int main() {
int iArray[5] = { 1, 2, 3, 4, 5 };
void printArray( iArray, 5 );
// Instantiated for int[]
char cArray[3] = { a, b, c };
void printArray( cArray, 3 );
// Instantiated for char[]
return 0;
}

Explicit Type Parameterization


A function template may not have any parameter
template <typename T>
T getInput() {
T x;
cin >> x;
return x;
}

Explicit Type Parameterization


int main() {
int x;
x = getInput();

// Error!

double y;
y = getInput();
}

// Error!

Explicit Type Parameterization


int main() {
int x;
x = getInput< int >();
double y;
y = getInput< double >();
}

User-defined Specializations
A template may not handle all the types successfully
Explicit specializations need to be provided for specific
type(s)

Example User Specializations


template< typename T >
bool isEqual( T x, T y ) {
return ( x == y );
}

Example User Specializations


int main {
isEqual( 5, 6 ); // OK
isEqual( 7.5, 7.5 ); // OK
isEqual( abc, xyz );
// Logical Error!
return 0;
}

Example User Specializations


template< >
bool isEqual< const char* >(
const char* x, const char* y ) {
return ( strcmp( x, y ) == 0 );
}

Example User Specializations


int main {
isEqual( 5, 6 );
// Target: general template
isEqual( 7.5, 7.5 );
// Target: general template
isEqual( abc, xyz );
// Target: user specialization
return 0;
}

References

Object Oriented Programming in C++, by Robert Lafore, published by


Sams Publishing (The Waite Group).

4th ed. available in soft form.

Object Oriented Programming Using C++ by Joyce Farrell , published by


Course Technology, Cengage Learning. 4th ed. available in soft form

National University of Computer & Emerging


Sciences ,FAST [www.nu.edu.pk]
Virtual University of Pakistan [ocw.vu.edu.pk]
Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
1/25/16

COMSATS Institute of Information Technology

637

Thanks

1/25/16

COMSATS Institute of Information Technology

638

LEC 20 TEMPLATE.CPP
// function template
#include <iostream>
using namespace std;
template <class T>
T GetMax (T a, T b)
{

T result;

result = (a>b)? a : b;

return (result);
}
int main ()
{
int i=5, j=6, k;
float l=10.5, m=5.6, n;
k=GetMax< int >(i,j);
n=GetMax< float >(l,m);

cout << k << endl;


cout << n << endl;
return 0;
}

EXE LEC 18
` // exp09_04.cpp (pub3)
// three classes derived from publication class
#include <iostream>
#include <string>
using namespace std;
enum disktype {CD, DVD};
////////////////////////////////////////////////////////////////
class publication
{
private:
string title;
float price;
public:
void getdata()
{
cout << "\n Enter title (one word only): ";

Potrebbero piacerti anche