2. Course Objective
► Objective of this course is to make students
familiar with the concepts of object-oriented
programming
► Concepts
will be reinforced by their
implementation in C++
4. Books
► C++ How to Program
By Deitel & Deitel
► The C++ Programming Language
By Bjarne Stroustrup
► Object-Oriented Software Engineering
By Jacobson, Christerson, Jonsson, Overgaard
10. …Example – OO Model
► Objects lives-in
Ali House
Ali
drives
House
Car
Car Tree
Tree
► Interactions
Ali lives in the house
Ali drives the car
11. Object-Orientation - Advantages
► People think in terms of objects
► OO models map to reality
► Therefore, OO models are
easy to develop
easy to understand
12. What is an Object?
An object is
► Something tangible (Ali, Car)
► Something that can be apprehended
intellectually (Time, Date)
13. … What is an Object?
An object has
► State (attributes)
► Well-defined behaviour (operations)
► Unique identity
14. Example – Ali is a Tangible Object
► State (attributes)
Name
Age
► behaviour (operations)
Walks
Eats
► Identity
His name
15. Example – Car is a Tangible Object
► State (attributes)
- Color
- Model
► behaviour (operations)
- Accelerate - Start Car
- Change Gear
► Identity
- Its registration number
16. Example – Time is an Object
Apprehended Intellectually
► State (attributes)
- Hours - Seconds
- Minutes
► behaviour (operations)
- Set Hours - Set Seconds
- Set Minutes
► Identity
- Would have a unique ID in the model
17. Example – Date is an Object
Apprehended Intellectually
► State (attributes)
- Year - Day
- Month
► behaviour (operations)
- Set Year - Set Day
- Set Month
► Identity
- Would have a unique ID in the model
19. Information Hiding
► Information is stored within the object
► It is hidden from the outside world
► It can only be manipulated by the object
itself
20. Example – Information Hiding
► Ali’s name is stored within his brain
► We can’t access his name directly
► Rather we can ask him to tell his name
21. Example – Information Hiding
►A phone stores several phone numbers
► Wecan’t read the numbers directly from the
SIM card
► Rather phone-set reads this information for
us
22. Information Hiding
Advantages
► Simplifies
the model by hiding
implementation details
► It is a barrier against change propagation
23. Encapsulation
► Data and behaviour are tightly coupled
inside an object
► Boththe information structure and
implementation details of its operations are
hidden from the outer world
24. Example – Encapsulation
► Alistores his personal information and
knows how to translate it to the desired
language
► We don’t know
How the data is stored
How Ali translates this information
25. Example – Encapsulation
►A Phone stores phone numbers in digital
format and knows how to convert it into
human-readable characters
► We don’t know
How the data is stored
How it is converted to human-readable
characters
27. Object has an Interface
► An object encapsulates data and behaviour
► So how objects interact with each other?
► Each object provides an interface
(operations)
► Other objects communicate through this
interface
28. Example – Interface of a Car
► Steer Wheels
► Accelerate
► Change Gear
► Apply Brakes
► Turn Lights On/Off
29. Example – Interface of a Phone
► Input Number
► Place Call
► Disconnect Call
► Add number to address book
► Remove number
► Update number
30. Implementation
► Provides services offered by the object
interface
► This includes
Data structures to hold object state
Functionality that provides required services
31. Example – Implementation of
Gear Box
► Data Structure
Mechanical structure of gear box
► Functionality
Mechanism to change gear
32. Example – Implementation of
Address Book in a Phone
► Data Structure
SIM card
► Functionality
Read/write circuitry
33. Separation of Interface &
Implementation
► Means change in implementation does not
effect object interface
► Thisis achieved via principles of information
hiding and encapsulation
34. Example – Separation of
Interface & Implementation
►A driver can drive a car independent of
engine type (petrol, diesel)
► Because
interface does not change with the
implementation
35. Example – Separation of
Interface & Implementation
►A driver can apply brakes independent of
brakes type (simple, disk)
► Again, reason is the same interface
36. Advantages of Separation
► Users need not to worry about a change
until the interface is same
► Low Complexity
► Directaccess to information structure of an
object can produce errors
37. Messages
► Objects communicate through messages
► They send messages (stimuli) by invoking
appropriate operations on the target object
► The number and kind of messages that can
be sent to an object depends upon its
interface
38. Examples – Messages
►A Person sends message (stimulus) “stop”
to a Car by applying brakes
►A Person sends message “place call” to a
Phone by pressing appropriate button
40. 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”
41. Example – Abstraction
Ali is a PhD student and teaches BS
students
► Attributes
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age
42. Example – Abstraction
Ali is a PhD student and teaches BS
students
► behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
43. Example – Abstraction
Student’s Perspective
► Attributes
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age
44. Example – Abstraction
Student’s Perspective
► behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
45. Example – Abstraction
Teacher’s Perspective
► Attributes
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age
46. Example – Abstraction
Teacher’s Perspective
► behaviour
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
47. Example – Abstraction
A cat can be viewed with different
perspectives
► Ordinary Perspective ► Surgeon’s Perspective
A pet animal with A being with
Four Legs A Skeleton
A Tail Heart
Two Ears Kidney
Sharp Teeth Stomach
49. Abstraction – Advantages
► Simplifies the model by hiding irrelevant
details
► Abstraction
provides the freedom to defer
implementation decisions by avoiding
commitment to details
50. Classes
► Inan OO model, some of the objects exhibit
identical characteristics (information
structure and behaviour)
► We say that they belong to the same class
51. 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
52. 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
53. Graphical Representation of Classes
(Class Name)
(Class Name)
(attributes)
Suppressed
(operations)
Form
Normal Form
54. Example – Graphical Representation
of Classes
Circle
center Circle
radius
draw Suppressed
computeArea Form
Normal Form
55. Example – Graphical Representation
of Classes
Person
name Person
age
gender Suppressed
eat Form
walk
Normal Form
56. Inheritance
►A child inherits characteristics of its parents
► Besides
inherited characteristics, a child
may have its own unique characteristics
57. 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
60. Inheritance – “IS A” or
“IS A KIND OF” Relationship
► Eachderived class is a special kind of its
base class
61. Example – “IS A” Relationship
Person
name
age
gender
eat
walk
Student Teacher Doctor
program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe
62. Example – “IS A” Relationship
Shape
color
coord
draw
rotate
setColor
Circle Triangle
radius Line angle
draw length draw
computeArea draw computeArea
64. 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
65. Example Reuse
Shape
color
coord
draw
rotate
setColor
Circle Triangle
radius Line angle
draw length draw
computeArea draw computeArea
66. Example Reuse
Person
name
age
gender
eat
walk
Student Teacher Doctor
program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe
67. Example Reuse
Person
name
age
gender
eat
walk
Student Teacher Doctor
program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe
69. Recap – Inheritance
► Derivedclass inherits all the characteristics
of the base class
► Besidesinherited characteristics, derived
class may have its own unique
characteristics
► Major benefit of inheritance is reuse
70. Concepts Related with
Inheritance
► Generalization
► Subtyping (extension)
► Specialization (restriction)
71. 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
72. Example – Generalization
Line
color
vertices Circle
length color
move vertices Triangle
setColor radius
color
getLength move
vertices
setColor
angle
computeArea
move
setColor
computeArea
73. Example – Generalization
Shape
color
vertices
move
setColor
Circle Triangle
radius Line angle
computeArea length computeArea
getLength
74. Example – Generalization
Student
name
age Teacher
gender name
Doctor
program age
name
studyYear gender
age
study designation
gender
heldExam salary
designation
eat teach
salary
walk takeExam
eat checkUp
walk prescribe
eat
walk
75. Example – Generalization
Person
name
age
gender
eat
walk
Student Teacher Doctor
program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe
76. 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
► Inheritthe new class from this class and
add unique behaviour to the new class
77. Sub-typing (Extension)
► Sub-typingmeans that derived class is
behaviourally compatible with the base class
► Behaviourallycompatible means that base
class can be replaced by the derived class
78. Person
name
age
gender
eats
Example – walks
Sub-typing
(Extension) Student
program
studyYear
study
takeExam
79. Shape
color
vertices
setColor
Example – move
Sub-typing
(Extension)
Circle
radius
computeCF
computeArea
80. Specialization (Restriction)
► Specialization
means that derived class is
behaviourally incompatible with the base
class
► Behaviourally incompatible means that base
class can’t always be replaced by the
derived class
81. Example – Specialization
(Restriction)
Person
age : [0..100]
…
setAge( a ) age = a
…
Adult If age < 18 then
age : [18..100] error
… else
setAge( a ) age = a
…
82. Example – Specialization
(Restriction)
IntegerSet
…
add( elem ) add element
… to the set
If elem < 1 then
NaturalSet error
… else
add( elem ) add element
… to the set
83. Overriding
►A class may need to override the default
behaviour provided by its base class
► Reasons for overriding
Provide behaviour specific to a derived class
Extend the default behaviour
Restrict the default behaviour
Improve performance
84. Example – Specific Behaviour
Shape
color
vertices
draw
move
setColor
Circle Triangle
radius Line angle
draw length draw
computeArea draw computeArea
85. Example – Extension
Window
width
height
open
close
draw
DialogBox 1- Invoke Window’s
controls draw
enable 2- draw the dialog
draw box
86. Example – Restriction
IntegerSet
…
add( elem ) Add element
… to the set
If elem < 1 then
NaturalSet give error
… else
add( elem ) Add element
… to the set
87. Example – Improve Performance
Shape
color
► Class Circle overrides coord
rotate operation of draw
class Shape with a Null rotate
operation. setColor
Circle
radius
draw
rotate
88. Abstract Classes
► An abstract class implements an abstract
concept
► Main purpose is to be inherited by other
classes
► Can’t be instantiated
► Promotes reuse
89. Example – Abstract Classes
Person
name
age
gender
eat
walk
Student Doctor
Teacher
► Here, Person is an abstract class
90. Example – Abstract Classes
Vehicle
color
model
accelerate
applyBrakes
Car Truck
Bus
► Here, Vehicle is an abstract class
91. Concrete Classes
►A concrete class implements a concrete
concept
► Main purpose is to be instantiated
► Provides
implementation details specific to
the domain context
92. Example – Concrete Classes
Person
Student Doctor
program Teacher
studyYear
study
heldExam
► Here,Student, Teacher and Doctor are
concrete classes
93. Example – Concrete Classes
Vehicle
Car Truck
Bus
capacity
load
unload
• Here, Car, Bus and Truck are concrete
classes
95. Class
► Class is a tool to realize objects
► Class is a tool for defining a new type
96. Example
► Lionis an object
► Student is an object
► Both has some attributes and some
behaviors
97. Uses
► The problem becomes easy to understand
► Interactions can be easily modeled
98. 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
99. Abstraction
► Only include details in the system that are
required for making a functional system
► Student
Name
Relevant to our problem
Address
Sibling
Not relevant to our problem
Father Business
100. Defining a New User Defined Type
class ClassName
{ Syntax
…
DataType MemberVariable;
ReturnType MemberFunction();
…
}; Syntax
101. Example
class Student
{
int rollNo;
char *name; Member variables
float CGPA;
Member Functions
char *address;
…
void setName(char *newName);
void setRollNo(int newRollNo);
…
};
102. Why Member Function
► They model the behaviors of an object
► Objects can make their data invisible
► Object remains in consistent state
104. Object and Class
► Objectis an instantiation of a user defined
type or a class
105. 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;
106. 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
107. Example
class Student{
int rollNo;
void setRollNo(int
aNo);
};
Student aStudent; Error
aStudent.rollNo;
109. 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
110. Example
class Student{
private:
char * name;
Cannot be accessed outside class
int rollNo;
public:
void setName(char *); Can be
accessed
void setRollNo(int); outside class
...
};
111. Example
class Student{
...
int rollNo;
public:
void setRollNo(int aNo);
};
int main(){
Student aStudent;
aStudent.SetRollNo(1);
}
112. Default access specifiers
► When no access specifier is mentioned then
by default the member is considered private
member
113. Example
class Student class Student
{ {
char * name; private:
int RollNo; char * name;
}; int RollNo;
};
114. Example
class Student
{
char * name;
int RollNo;
void SetName(char *);
}; Error
Student aStudent;
aStudent.SetName(Ali);
115. Example
class Student
{
char * name;
int RollNo;
public:
void setName(char *);
};
Student aStudent;
aStudent.SetName(“Ali”);
Hinweis der Redaktion
class is a keyword and must always be in small caps Omitting the semicolon at the end is a syntax error 13:22
Accessing a private member from outside member function is a syntax error You can use access specifiers as many times as you like Each access specifier must be followed by a ‘:’