0% found this document useful (0 votes)
18 views

Lecture01-22

Uploaded by

Abdullah Ilyas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Lecture01-22

Uploaded by

Abdullah Ilyas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 334

Object-Oriented Programming

(OOP)
Lecture No. 1

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

1
Course Contents
► Object-Orientation
► Objects and Classes
► Overloading
► Inheritance
► Polymorphism
► Generic Programming
► Exception Handling
► Introduction to Design Patterns

Books
► C++ How to Program
By Deitel & Deitel

► The C++ Programming Language


By Bjarne Stroustrup

► Object-Oriented Software Engineering


By Jacobson, Christerson, Jonsson, Overgaard

2
Grading Policy

► Assignments 15 %
► Group Discussion 5%
► Mid-Term 35 %
► Final 45 %

Object-Orientation (OO)

3
What is Object-Orientation?

►A technique for system modeling

► OO model consists of several interacting


objects

What is a Model?

►A model is an abstraction of something

► Purposeis to understand the product before


developing it

4
Examples – Model

► Highway maps

► Architectural models

► Mechanical models

Example – OO Model

5
…Example – OO Model
lives-in
► Objects Ali House
ƒ Ali
drives
ƒ House
ƒ Car
Car Tree
ƒ Tree
► Interactions
ƒ Ali lives in the house
ƒ Ali drives the car

Object-Orientation - Advantages
► People think in terms of objects

► OO models map to reality

► Therefore, OO models are


ƒ easy to develop
ƒ easy to understand

6
What is an Object?
An object is

► Something tangible (Ali, Car)

► Something that can be apprehended


intellectually (Time, Date)

… What is an Object?
An object has

► State (attributes)
► Well-defined behaviour (operations)
► Unique identity

7
Example – Ali is a Tangible Object

► State (attributes)
ƒ Name
ƒ Age
► behaviour (operations)
ƒ Walks
ƒ Eats
► Identity
ƒ His name

Example – Car is a Tangible Object

► State (attributes)
- Color
- Model
► behaviour (operations)
- Accelerate - Start Car
- Change Gear
► Identity
- Its registration number

8
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

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

9
Object-Oriented Programming
(OOP)
Lecture No. 2

Information Hiding

► Information is stored within the object

► It is hidden from the outside world

► It can only be manipulated by the object


itself

1
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

Example – Information Hiding

►A phone stores several phone numbers

► We can’t read the numbers directly from the


SIM card

► Rather phone-set reads this information for


us

2
Information Hiding
Advantages

► Simplifies
the model by hiding
implementation details

► It is a barrier against change propagation

Encapsulation

► Data and behaviour are tightly coupled


inside an object

► Both the information structure and


implementation details of its operations are
hidden from the outer world

3
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

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

4
Encapsulation – Advantages

► Simplicity and clarity

► Low complexity

► Better understanding

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

5
Example – Interface of a Car
► Steer Wheels
► Accelerate
► Change Gear
► Apply Brakes
► Turn Lights On/Off

Example – Interface of a Phone


► Input Number
► Place Call
► Disconnect Call
► Add number to address book
► Remove number
► Update number

6
Implementation
► Provides services offered by the object
interface

► This includes
ƒ Data structures to hold object state
ƒ Functionality that provides required services

Example – Implementation of
Gear Box

► Data Structure
ƒ Mechanical structure of gear box

► Functionality
ƒ Mechanism to change gear

7
Example – Implementation of
Address Book in a Phone

► Data Structure
ƒ SIM card

► Functionality
ƒ Read/write circuitry

Separation of Interface &


Implementation

► Means change in implementation does not


effect object interface

► Thisis achieved via principles of information


hiding and encapsulation

8
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

Example – Separation of
Interface & Implementation

►A driver can apply brakes independent of


brakes type (simple, disk)

► Again, reason is the same interface

9
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

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

10
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

11
Object-Oriented Programming
(OOP)
Lecture No. 3

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

Example – Abstraction
Ali is a PhD student and teaches BS
students

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

2
Example – Abstraction
Student’s Perspective

► Attributes
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age

Example – Abstraction
Student’s Perspective

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

3
Example – Abstraction
Teacher’s Perspective

► Attributes
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age

Example – Abstraction
Teacher’s Perspective

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

4
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

Example – Abstraction

Engineer’s View

Driver’s View

5
Abstraction – Advantages

► Simplifies the model by hiding irrelevant


details

► Abstraction
provides the freedom to defer
implementation decisions by avoiding
commitment to details

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

6
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

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

7
Graphical Representation of Classes

(Class Name)
(Class Name)
(attributes)

Suppressed
(operations)
Form

Normal Form

Example – Graphical Representation


of Classes

Circle
center Circle
radius
draw Suppressed
computeArea Form

Normal Form

8
Example – Graphical Representation
of Classes

Person
name Person
age
gender Suppressed
eat Form
walk

Normal Form

Inheritance

►A child inherits characteristics of its parents

► Besides
inherited characteristics, a child
may have its own unique characteristics

9
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

Example – Inheritance

Person

Student Doctor
Teacher

10
Example – Inheritance

Shape

Line Triangle
Circle

Inheritance – “IS A” or
“IS A KIND OF” Relationship

► Eachderived class is a special kind of its


base class

11
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

Example – “IS A” Relationship


Shape
color
coord
draw
rotate
setColor

Circle Triangle
radius Line angle
draw length draw
computeArea draw computeArea

12
Inheritance – Advantages

► Reuse

► Less redundancy

► Increased maintainability

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

13
Example Reuse
Shape
color
coord
draw
rotate
setColor

Circle Triangle
radius Line angle
draw length draw
computeArea draw computeArea

Example Reuse
Person
name
age
gender
eat
walk

Student Teacher Doctor


program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe

14
Example Reuse
Person
name
age
gender
eat
walk

Student Teacher Doctor


program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe

15
Object-Oriented Programming
(OOP)
Lecture No. 4

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

1
Concepts Related with
Inheritance

► Generalization

► Subtyping (extension)

► Specialization (restriction)

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

2
Example – Generalization
Line
color
vertices Circle
length color
move vertices Triangle
setColor radius
color
getLength move
vertices
setColor
angle
computeArea
move
setColor
computeArea

Example – Generalization
Shape
color
vertices
move
setColor

Circle Triangle
radius Line angle
computeArea length computeArea
getLength

3
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

Example – Generalization
Person
name
age
gender
eat
walk

Student Teacher Doctor


program designation designation
studyYear salary salary
study teach checkUp
heldExam takeExam prescribe

4
Sub-typing & Specialization
► Wewant to add a new class to an existing
model

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

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

5
Person
name
age
gender
eats
Example – walks

Sub-typing
(Extension) Student
program
studyYear
study
takeExam

Shape
color
vertices
setColor
Example – move

Sub-typing
(Extension)
Circle
radius
computeCF
computeArea

6
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

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

7
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

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

8
Example – Specific Behaviour
Shape
color
vertices
draw
move
setColor

Circle Triangle
radius Line angle
draw length draw
computeArea draw computeArea

Example – Extension
Window
width
height
open
close
draw

DialogBox 1- Invoke Window’s


controls
draw
enable 2- draw the dialog
draw box

9
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

Example – Improve Performance


Shape
color
► Class Circle overrides coord
rotate operation of draw
class Shape with a Null rotate
setColor
operation.

Circle
radius
draw
rotate

10
Abstract Classes

► An abstract class implements an abstract


concept
► Main purpose is to be inherited by other
classes
► Can’t be instantiated
► Promotes reuse

Example – Abstract Classes


Person
name
age
gender
eat
walk

Student Doctor
Teacher
► Here, Person is an abstract class

11
Example – Abstract Classes
Vehicle
color
model
accelerate
applyBrakes

Car Truck
Bus

► Here, Vehicle is an abstract class

Concrete Classes
►A concrete class implements a concrete
concept

► Main purpose is to be instantiated

► Provides
implementation details specific to
the domain context

12
Example – Concrete Classes

Person

Student Doctor
program Teacher
studyYear
study
heldExam

► Here,Student, Teacher and Doctor are


concrete classes

Example – Concrete Classes

Vehicle

Car Truck
Bus
capacity
load
unload

• Here, Car, Bus and Truck are concrete


classes

13
Object-Oriented Programming
(OOP)
Lecture No. 5

Multiple Inheritance

► Wemay want to reuse characteristics of


more than one parent class

1
Example – Multiple Inheritance

Mermaid

Example – Multiple Inheritance

Woman Fish

Mermaid

2
Example – Multiple Inheritance

Amphibious Vehicle

Example – Multiple Inheritance

Vehicle

Land Vehicle Water Vehicle

Car Amphibious Vehicle Boat

3
Problems with Multiple
Inheritance

► Increased complexity

► Reduced understanding

► Duplicate features

Problem – Duplicate Features

Woman Fish
eat eat
… …

Mermaid

► Which eat operation Mermaid inherits?

4
Solution – Override the Common
Feature

Woman Fish
eat eat
… …

Mermaid
eat Invoke eat
operation of
… desired class

Problem – Duplicate Features


(Diamond Problem)
Vehicle
changeGear

Land Vehicle Water Vehicle

Car Amphibious Vehicle Boat

► Which changeGear operation Amphibious


Vehicle inherits?

5
Solution to Diamond Problem

► Some languages disallow diamond


hierarchy

► Others provide mechanism to ignore


characteristics from one side

Association
► Objectsin an object model interact with
each other

► Usuallyan object provides services to


several other objects

► Anobject keeps associations with other


objects to delegate tasks

6
Kinds of Association
► Class Association
ƒ Inheritance

► Object Association
ƒ Simple Association
ƒ Composition
ƒ Aggregation

Simple Association

► Is the weakest link between objects

► Isa reference by which one object can


interact with some other object

► Is simply called as “association”

7
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

One-way Association

► We can navigate along a single direction


only

► Denoted by an arrow towards the server


object

8
Example – Association

lives-in
Ali House
1 1

► Ali lives in a House

Example – Association

drives
Ali Car
1 *

► Ali drives his Car

9
Two-way Association

► We can navigate in both directions

► Denoted by a line between the associated


objects

Example – Two-way Association

works-for
Employee Company
* 1

► Employeeworks for company


► Company employs employees

10
Example – Two-way Association

friend
Yasir Ali
1 1

► Yasir is a friend of Ali


► Ali is a friend of Yasir

Binary Association

► Associates objects of exactly two classes

► Denoted by a line, or an arrow between the


associated objects

11
Example – Binary Association

works-for
Employee Company
* 1

► Association“works-for” associates objects of


exactly two classes

Example – Binary Association

drives
Ali Car
1 *

► Association“drives” associates objects of


exactly two classes

12
Ternary Association

► Associates objects of exactly three classes

► Denoted by a diamond with lines connected


to associated objects

Example – Ternary Association

Student 1
Teacher
*

*
Course

► Objects of exactly three classes are


associated

13
Example – Ternary Association

Project * *
Language

1
Person

► Objects of exactly three classes are


associated

N-ary Association

► An association between 3 or more classes

► Practical examples are very rare

14
Composition
► An object may be composed of other
smaller objects
► The relationship between the “part” objects
and the “whole” object is known as
Composition
► Composition is represented by a line with a
filled-diamond head towards the composer
object

Example – Composition of Ali


Head
1

Arm Ali Leg


2 2

1
Body

15
Example – Composition of Chair
Back
1

Chair

2 1 4
Arm Seat Leg

Composition is Stronger

► Composition is a stronger relationship,


because
ƒ Composed object becomes a part of the
composer
ƒ Composed object can’t exist independently

16
Example – Composition is
Stronger

► Ali is made up of different body parts

► They can’t exist independent of Ali

Example – Composition is
Stronger

► Chair’s body is made up of different parts

► They can’t exist independently

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

Example – Aggregation

Bed
1

Chair Room Table


* 1

1
Cupboard

18
Example – Aggregation

Garden * Plant

Aggregation is Weaker

► Aggregation is weaker relationship, because


ƒ Aggregate object is not a part of the container
ƒ Aggregate object can exist independently

19
Example – Aggregation is Weaker

► Furniture is not an intrinsic part of room

► Furniturecan be shifted to another room,


and so can exist independent of a particular
room

Example – Aggregation is Weaker

►A plant is not an intrinsic part of a garden

► Itcan be planted in some other garden, and


so can exist independent of a particular
garden

20
Object-Oriented Programming
(OOP)
Lecture No. 6

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
…Class Compatibility
► Derived class is usually a subtype of the
base class

► Itcan handle all the legal messages


(operations) of the base class

► Therefore, base class can always be


replaced by the derived class

Example – Class Compatibility


Shape
color
vertices
move
setColor
draw

Circle Triangle
radius Line angle
length
draw draw
computeArea draw computeArea
getLength

2
Example – Class Compatibility
File
size

open
print

ASCII File PS File


… PDF File …

print print
… print …

Polymorphism

► Ingeneral, polymorphism refers to


existence of different forms of a single
entity

► For example, both Diamond and Coal are


different forms of Carbon

3
Polymorphism in OO Model

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

Example – Polymorphism

draw Shape
View
draw

Line Circle Triangle


draw draw draw

4
Example – Polymorphism

print File
Editor
print

ASCII File PDF File PS File


print print print

Polymorphism – Advantages
► Messagescan be interpreted in different
ways depending upon the receiver class

draw Shape
View
draw

Line Circle Triangle


draw draw draw

5
Polymorphism – Advantages
► New classes can be added without changing
the existing model

draw Shape
View
draw

Square Line Circle Triangle


draw draw draw draw

Polymorphism – Advantages

► Ingeneral, polymorphism is a powerful tool


to develop flexible and reusable systems

6
Object-Oriented Modeling

An Example

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.

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

…Identify Classes
¾ Eliminate irrelevant classes

► Editor – Very broad scope

► User – Out of system boundary

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

…Identify Classes
¾Following classes have been identified:

► Shape • Group
► Line • View
► Circle
► Triangle
► Menu

9
Object Model – Graphic Editor

Shape Group

Line Menu

Circle
View

Triangle

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)

10
… Identify Associations
¾ Verify access paths

► View contains shapes


ƒ View contains lines
ƒ View contains circles
ƒ View contains triangles
ƒ View contains groups
(Aggregation)

… Identify Associations
¾ Verify access paths

► Menu sends message to View


(Simple One-Way Association)

11
Object Model – Graphic Editor

Menu View Shape


n
n

n n n
Line n Circle Triangle Group
n
n n

Identify Attributes
¾ Extract properties of the object
ƒ From the problem statement

► Properties are not mentioned

12
…Identify Attributes
¾ Extract properties of the object
ƒ From the domain knowledge

• Line • Triangle
– Color – Color
– Vertices – Vertices
– Length – Angle
• Circle • Shape
– Color – Color
– Vertices – Vertices
– Radius

…Identify Attributes
¾ Extract properties of the object
ƒ From the domain knowledge

• Group • Menu
– noOfObjects – Name
• View – isOpen
– noOfObjects
– selected

13
Object Model – Graphic Editor

Menu View Shape


name noOfObjects color
isOpen selected n vertices

n n n
Line n Circle Triangle Group
length radius angle noOfObjects
n
n
n

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.

14
… Identify Operations
¾ Eliminate irrelevant operations

► Develop – out of system boundary

► Behave – have broad semantics

…Identify Operations
¾ Following are selected operations:

• Line • Circle
– Draw – Draw
– Select – Select
– Move – Move
– Rotate – Rotate

15
…Identify Operations
¾ Following are selected operations:

• Triangle • Shape
– Draw – Draw
– Select – Select
– Move – Move
– Rotate – Rotate

…Identify Operations
¾ Following are selected operations:

• Group • Menu
– Draw – Open
– Select – Select
– Move – Move
– Rotate – Rotate

16
…Identify Operations
¾ Extract operations using domain
knowledge

• View
– Add – Select
– Remove – Move
– Group – Rotate
– Show

View
Menu noOfObjects Shape
selected
name color
isOpen vertices
add()
remove()
open() n draw()
group()
select() select()
show()
move() move()
select()
rotate() rotate()
move()
rotate() n

n n
Line n Triangle Group
n
length angle noOfObjects
Circle
n
draw() radius draw() draw()
n
n draw()

17
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

…Identify Inheritance

¾ By analyzing requirements

► “Individual shapes can be grouped together


and can behave as a single shape”
ƒ Group inherits from Shape

18
Refining the Object Model
► Applicationof inheritance demands an
iteration over the whole object model

► In the inheritance hierarchy,


ƒ All attributes are shared
ƒ All associations are shared
ƒ Some operations are shared
ƒ Others are overridden

…Refining the Object Model

¾ Share associations

► View contains all kind of shapes

► Group consists of all kind of shapes

19
…Refining the Object Model

¾ Share attributes

► Shape – Line, Circle, Triangle and Group


ƒ Color, vertices

…Refining the Object Model

¾ Share operations

► Shape – Line, Circle, Triangle and Group


ƒ Select
ƒ Move
ƒ Rotate

20
…Refining the Object Model

¾ Share the interface and override


implementation

► Shape – Line, Circle, Triangle and Group


ƒ Draw

View
Menu noOfObjects Shape
selected
name color
isOpen vertices
add()
remove()
open() n draw() n
group()
select() select()
show()
move() move()
select()
rotate() rotate()
move()
rotate()

Line Circle Triangle Group


length radius angle noOfObjects

draw() draw() draw() draw()

21
View
Menu noOfObjects Shape
selected
name color
isOpen vertices
add()
remove()
open() n draw()
group()
select() select()
show()
move() move()
select()
rotate() rotate()
move()
rotate() n

n n
Line n Triangle Group
n
length angle noOfObjects
Circle
n
draw() radius draw() draw()
n
n draw()

22
Object oriented programming
(OOP)
Lecture No. 7

Class
► Class is a tool to realize objects
► Class is a tool for defining a new type

1
Example
► Lionis an object
► Student is an object
► Both has some attributes and some
behaviors

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

2
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

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

3
Defining a New User Defined Type
class ClassName
{ Syntax

DataType MemberVariable;
ReturnType MemberFunction();

}; Syntax

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

char *address;

void setName(char *newName);
void setRollNo(int newRollNo);

};

4
Why Member Function
► They model the behaviors of an object
► Objects can make their data invisible
► Object remains in consistent state

Example
Student aStudent;

aStudent.rollNo = 514;

aStudent.rollNo = -514; //Error

5
Object and Class
► Objectis an instantiation of a user defined
type or a class

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;

6
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

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

Student aStudent; Error


aStudent.rollNo;

7
Access specifiers

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

8
Example
class Student{
private:
char * name;
Cannot be accessed outside class
int rollNo;
public:
void setName(char *); Can be
void setRollNo(int); accessed
outside class
...
};

Example
class Student{
...
int rollNo;
public:
void setRollNo(int aNo);
};
int main(){
Student aStudent;
aStudent.SetRollNo(1);
}

9
Default access specifiers
► When no access specifier is mentioned then
by default the member is considered private
member

Example
class Student class Student
{ {
char * name; private:
int RollNo; char * name;
}; int RollNo;
};

10
Example
class Student
{
char * name;
int RollNo;
void SetName(char *);
}; Error
Student aStudent;
aStudent.SetName(Ali);

Example
class Student
{
char * name;
int RollNo;
public:
void setName(char *);
};
Student aStudent;
aStudent.SetName(“Ali”);

11
Object Oriented Programming
(OOP)
Lecture No. 8

Review
► Class
ƒ Concept
ƒ Definition
► Data members
► Member Functions
► Access specifier

1
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

2
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

3
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

4
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

5
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

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

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

8
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

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

}
};

10
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

11
Example
class Student
{
int rollNo;
char *name;
float GPA;
public:
… //no constructors
};

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

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

13
Example
Student::Student(int aRollNo,
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);
}

14
Constructor Overloading
► Use default parameter value to reduce the
writing effort

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

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

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

16
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

17
Example

Student studentA;
Student studentB = studentA;

studentA Memory
studentB
Name A
Name
RollNo H
RollNo
GPA M GPA
A
D

Copy Constructor (contd.)


Student::Student(
const Student & obj){
int len = strlen(obj.name);
name = new char[len+1]
strcpy(name, obj.name);

//copy rest of the data members
}

18
Copy Constructor (contd.)
► Copy constructor is normally used to
perform deep copy
► If we do not make a copy constructor then
the compiler performs shallow copy

Example
Memory A
Student studentA; A Name
Student studentB = studentA; H RollNo
M GPA
A
D B
A Name
H RollNo
M GPA
A
D

19
Object Oriented Programming
(OOP)
Lecture No. 9

Review

►Member functions implementation


►Constructors
►Constructors overloading
►Copy constructors

1
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(“Ahmad”);
Student studentB = studentA;
func1(studentA);
}

2
Copy Constructor (contd.)

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

3
Example
Student studentA(“Ahmad”);
Student studentB = studentA;

A
H
studentA M studentB
A
RollNn D RollNn
Name Name
Heap
GPA GPA

Example
int main(){
Student studentA(“Ahmad”,1);
{
Student studentB = studentA;

A
H
studentA M studentB
A
RollNn D RollNn
Name Name
Heap
GPA GPA

4
Example
int main(){
Student studentA(“Ahmad”,1);
{
Student studentB = studentA;
}
}

studentA
RollNn
Name
Heap
GPA

Copy Constructor (contd.)

Student::Student(
const Student & obj){
int len = strlen(obj.name);
name = new char[len+1]
strcpy(name, obj.name);

/*copy rest of the data members*/
}

5
Example
int main(){
Student studentA(“Ahmad”,1);
{
Student studentB = studentA;
A
H
M studentB
studentA A
D RollNn
RollNn
A Name
Name H GPA
GPA M
A
D

Example
int main(){
Student studentA(“Ahmad”,1);
{
Student studentB = studentA;
}
} A
H
M
studentA A
RollNn D

Name
Heap
GPA

6
Copy Constructor (contd.)

►Copy constructor is normally used


to perform deep copy
►If we do not make a copy
constructor then the compiler
performs shallow copy

Destructor

►Destructor is used to free memory


that is allocated through dynamic
allocation
►Destructor is used to perform
house keeping operations

7
Destructor (contd.)

►Destructor is a function with


the same name as that of
class, but preceded with a
tilde ‘~’

Example
class Student
{

public:
~Student(){
if(name){
delete []name;
}
}
}

8
Overloading

►Destructors cannot be
overloaded

Sequence of Calls
►Constructors and destructors are
called automatically
►Constructors are called in the
sequence in which object is
declared
►Destructors are called in reverse
order

9
Example
Student::Student(char * aName){

cout << aName << “Cons\n”;
}
Student::~Student(){
cout << name << “Dest\n”;
}
};

Example
int main()
{
Student studentB(“Ali”);
Student studentA(“Ahmad”);
return 0;
}

10
Example

Output:
Ali Cons
Ahmad Cons
Ahmad Dest
Ali Dest

Accessor Functions
►Usually the data member are defined
in private part of a class – information
hiding
►Accessor functions are functions that
are used to access these private data
members
►Accessor functions also useful in
reducing error

11
Example – Accessing Data
Member
class Student{

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

Example – Avoiding Error


void Student::setRollNo(int
aRollNo){
if(aRollNo < 0){
rollNo = 0;
}
else
{
rollNo = aRollNo;
}
}

12
Example - Getter
class Student{

int rollNo;
public:
int getRollNo(){
return rollNo;
}
};

this Pointer
class Student{
int rollNo;
char *name;
float GPA;
public:
int getRollNo();
void setRollNo(int aRollNo);

};

13
this Pointer
►The compiler reserves space for the
functions defined in the class
►Space for data is not allocated (since
no object is yet created)

Function Space
getRollNo(), …

this Pointer
►Student s1, s2, s3;

s2(rollNo,…)

Function Space
getRollNo(), … s3(rollNo,…)

s1(rollNo,…)

14
this Pointer
►Function space is common for
every variable
►Whenever a new object is created:
ƒ Memory is reserved for variables
only
ƒ Previously defined functions are
used over and over again

this Pointer
►Memory layout for objects
created:
s1
rollNo, …
s2
rollNo, …
s3
rollNo, …
s4
rollNo, …

Function Space
getRollNo(), …

•How does the functions know on which


object to act?

15
this Pointer
► Address of each object is passed to the
calling function
► This address is deferenced by the functions
and hence they act on correct objects

s1 s2 s3 s4
rollNo, … rollNo, … rollNo, … rollNo, …
address address address address

•The variable containing the “self-address”


is called this pointer

Passing this Pointer


► Whenever a function is called the this
pointer is passed as a parameter to that
function
► Function with n parameters is actually called
with n+1 parameters

16
Example
void Student::setName(char *)

is internally represented as

void Student::setName(char *,
const Student *)

Declaration of this
DataType * const this;

17
Compiler Generated Code
Student::Student(){
rollNo = 0;
}

Student::Student(){
this->rollNo = 0;
}

18
Object Oriented Programming
(OOP)
Lecture No. 10

Review

►Copy constructors
►Destructor
►Accessor Functions
►this Pointer

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

Example
Student Student::setRollNo(int aNo)
{

return *this;
}
Student Student::setName(char *aName)
{

return *this;
}

2
Example
int main()
{
Student aStudent;
aStudent;
Student bStudent;
bStudent;

bStudent = aStudent.setName(“
aStudent.setName(“Ahmad”
Ahmad”);

bStudent = aStudent.setName(“
aStudent.setName(“Ali”
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

3
Complex Number
►There are two representations of
complex number
ƒ Euler form
►z =x+iy
ƒ 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 New


implementation
Complex Complex
float x float z
float y float theta
float getX() float getX()
float getY() float getY()
void setNumber void setNumber
(float i, float j) (float i, float j)
… …

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

}

};

5
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

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

}

7
Driver.cpp
#include “student.h”

int main(){
Student aStudent;
}

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

8
const Member Functions

►Keyword const is placed at the


end of the parameter list

const Member Functions


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

Definition:
ReturnVal ClassName::Function() const{

}

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

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

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

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

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

const Functions

►Constructors and Destructors


cannot be const
►Constructor and destructor are
used to modify the object to a well
defined state

12
Example
class Time{
public:
Time() const {} //error…
~Time() const {} //error…
};

const Function
►Constant member function
cannot change data member
►Constant member function
cannot access non-constant
member functions

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

this Pointer and const Member


Function
►thispointer is passed as constant
pointer to const data in case of
constant member functions
const Student *const this;
instead of
Student * const this;

14
Object Oriented Programming
(OOP)
Lecture No. 11

Review
► this
Pointer
► Separation of interface and implementation
► Constant member functions

1
Problem

►Change the class Student such


that a student is given a roll
number when the object is
created and cannot be changed
afterwards

Student Class
class Student{

int rollNo;
public:
Student(int aNo);
int getRollNo();
void setRollNo(int aNo);

};

2
Modified Student Class
class Student{

const int rollNo;
public:
Student(int aNo);
int getRollNo();
void setRollNo(int aNo);

};

Example
Student::Student(int aRollNo)
{
rollNo = aRollNo;
/*error: cannot modify a
constant data member*/
}

3
Example
void Student::SetRollNo(int i)
{
rollNo = i;
/*error: cannot modify a
constant data member*/
}

Member Initializer List


►A member initializer list is a mechanism
to initialize data members
►It is given after closing parenthesis of
parameter list of constructor
►In case of more then one member use
comma separated list

4
Example
class Student{
const int rollNo;
rollNo;
char *name;
float GPA;
public:
Student(int aRollNo)
aRollNo)
: rollNo(aRollNo),
rollNo(aRollNo), name(Null), GPA(0.0){

}

};

Order of Initialization
► Data member are initialized in order they
are declared
► Order in member initializer list is not
significant at all

5
Example
class ABC{
int x;
int y;
int z;
public:
ABC();
};

Example
ABC::ABC():y(10),x(y),z(y)
{

}
/* x = Junk value
y = 10
z = 10 */

6
const Objects
►Objects can be declared
constant with the use of const
keyword
►Constant objects cannot change
their state

Example
int main()
{
const Student aStudent;
return 0;
}

7
Example
class Student{

int rollNo;
public:

int getRollNo(){
return rollNo;
}
};

Example
int main(){
const Student aStudent;
int a = aStudent.getRollNo();
//error
}

8
const Objects

►const objects cannot access


“non const” member function
►Chances of unintentional
modification are eliminated

Example
class Student{

int rollNo;
public:

int getRollNo()const{
return rollNo;
}
};

9
Example
int main(){
const Student aStudent;
int a = aStudent.getRollNo();
}

Constant data members

► Make all functions that don’t change the


state of the object constant
► This will enable constant objects to access
more member functions

10
Static Variables

►Lifetime of static variable is


throughout the program life
►If static variables are not explicitly
initialized then they are initialized
to 0 of appropriate type

Example
void func1(int i){
static int staticInt = i;
cout << staticInt << endl;
}
int main(){
func1(1); Output:
func1(2); 1
} 1

11
Static Data Member

Definition
“A variable that is part of a
class, yet is not part of an
object of that class, is called
static data member”

Static Data Member

►They are shared by all


instances of the class
►They do not belong to any
particular instance of a class

12
Class vs. Instance Variable
►Student s1, s2, s3;

s2(rollNo,…) Instance Variable


Class
Variable
Class Space s3(rollNo,…)

s1(rollNo,…)

Static Data Member (Syntax)

►Keyword static is used to make a


data member static

class ClassName{

static DataType VariableName;
};

13
Defining Static Data Member

►Static data member is declared


inside the class
►But they are defined outside the
class

Defining Static Data Member


class ClassName{

static DataType VariableName;
};

DataType ClassName::VariableName;

14
Initializing Static Data Member

►Static data members should be


initialized once at file scope
►They are initialized at the time
of definition

Example
class Student{
private:
static int noOfStudents;
public:

};
int Student::noOfStudents = 0;
/*private static member cannot be
accessed outside the class except for
initialization*/

15
Initializing Static Data Member

►If static data members are not


explicitly initialized at the time
of definition then they are
initialized to 0

Example
int Student::noOfStudents;

is equivalent to

int Student::noOfStudents=0;

16
Object Oriented Programming
(OOP)
Lecture No. 12

Review
► Constant data members
► Constant objects
► Static data members

1
Static Data Member
Definition
“A variable that is part of a class, yet is not
part of an object of that class, is called
static data member”

Static Data Member

►They are shared by all


instances of the class
►They do not belong to any
particular instance of a class

2
Class vs. Instance Variable
► Student s1, s2, s3;

s2(rollNo,…) Instance Variable


Class
Variable
Class Space s3(rollNo,…)

s1(rollNo,…)

Static Data Member (Syntax)

► Keywordstatic is used to make a data


member static

class ClassName{

static DataType VariableName;
};

3
Defining Static Data Member

► Static data member is declared inside the


class
► But they are defined outside the class

Defining Static Data Member


class ClassName{

static DataType VariableName;
};

DataType ClassName::VariableName;

4
Initializing Static Data Member

►Static data members should be


initialized once at file scope
►They are initialized at the time
of definition

Example
class Student{
private:
static int noOfStudents;
noOfStudents;
public:

};
int Student::noOfStudents = 0;
/*private static member cannot be accessed outside the
class except for initialization*/

5
Initializing Static Data Member

►If static data members are not


explicitly initialized at the time
of definition then they are
initialized to 0

Example
int Student::noOfStudents;

is equivalent to

int Student::noOfStudents=0;

6
Accessing Static Data Member

► To access a static data member there are


two ways
ƒ Access like a normal data member
ƒ Access using a scope resolution operator ‘::’

Example
class Student{
public:
static int noOfStudents;
noOfStudents;
};
int Student::noOfStudents;
Student::noOfStudents;
int main(){
Student aStudent;
aStudent;
aStudent.noOfStudents = 1;
Student::noOfStudents = 1;
}

7
Life of Static Data Member
► They are created even when there is no
object of a class
► They remain in memory even when all
objects of a class are destroyed

Example
class Student{
public:
static int noOfStudents;
noOfStudents;
};
int Student::noOfStudents;
Student::noOfStudents;
int main(){
Student::noOfStudents = 1;
}

8
Example
class Student{
public:
static int noOfStudents;
noOfStudents;
};
int Student::noOfStudents;
Student::noOfStudents;
int main(){
{
Student aStudent;
aStudent;
aStudent.noOfStudents = 1;
}
Student::noOfStudents = 1;
}

Uses

►They can be used to store


information that is required by
all objects, like global variables

9
Example

►Modify the class Student such


that one can know the number
of student created in a system

Example
class Student{

public:
static int noOfStudents;
noOfStudents;
Student();
~Student();

};
int Student::noOfStudents = 0;

10
Example
Student::Student(){
noOfStudents++;
}
Student::~Student(){
noOfStudents--;
}

Example
int Student::noOfStudents = 0;
int main(){
cout <<Student::noOfStudents
<<Student::noOfStudents <<endl
<<endl;
;
Student studentA;
studentA;
cout <<Student::noOfStudents
<<Student::noOfStudents <<endl
<<endl;
;
Student studentB;
studentB;
cout <<Student::noOfStudents
<<Student::noOfStudents <<endl
<<endl;
;
}

Output:
0
1
2

11
Problem
► noOfStudents is accessible outside the class
► Bad design as the local data member is kept
public

Static Member Function


Definition:
“The function that needs access to the
members of a class, yet does not need
to be invoked by a particular object, is
called static member function”

12
Static Member Function
► They are used to access static data
members
► Access mechanism for static member
functions is same as that of static data
members
► They cannot access any non-static members

Example
class Student{
static int noOfStudents;
noOfStudents;
int rollNo;
rollNo;
public:
static int getTotalStudent(){
return noOfStudents;
noOfStudents;
}
};
int main(){
int i = Student::getTotalStudents();
}

13
Accessing non static data members
int Student::getTotalStudents(){
return rollNo;
rollNo;
}
int main(){
int i = Student::getTotalStudents();
/*Error: There is no instance of Student,
rollNo cannot be accessed*/
}

this Pointer
► this pointer is passed implicitly to member
functions
► this pointer is not passed to static member
functions
► Reason is static member functions cannot
access non static data members

14
Global Variable vs. Static Members

►Alternative to static member is to use


global variable
►Global variables are accessible to all
entities of the program
ƒ Against information hiding

Array of Objects
► Array of objects can only be created if an
object can be created without supplying an
explicit initializer
► There must always be a default constructor
if we want to create array of objects

15
Example
class Test{
public:
};
int main(){
Test array[2]; // OK
}

Example
class Test{
public:
Test();
};
int main(){
Test array[2]; // OK
}

16
Example
class Test{
public:
Test(int i);
};
int main(){
Test array[2]; // Error
}

Example
class Test{
public:
Test(int i);
}
int main(){
Test array[2] =
{Test(0),Test(0)};
}

17
Example
class Test{
public:
Test(int i);
}
int main(){
Test a(1),b(2);
Test array[2] = {a,b};
}

18
Object Oriented Programming
(OOP)
Lecture No. 13

Review
► Static data members
► Static member functions
► Array of objects

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

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

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

4
Example
int main()
{
Student *ptr
*ptr = new Student[100];
for(int i = 0; i < 100;i++)
{
ptr-
ptr->setRollNo(10);
}
return 0;
}

Breakup of new Operation

► new operator is decomposed as follows


ƒ Allocating space in memory
ƒ Calling the appropriate constructor

5
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
► Attributesthat can be seen in this problem
statement are
ƒ Day
ƒ Month
ƒ Year
ƒ Default date

6
Attributes
► Thedefault 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;

};

7
Interfaces
► getDay ► addDay
► getMonth ► addMonth
► getYear ► addYear
► setDay ► setDefaultDate
► setMonth
► setYear

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

8
Interfaces in Date.h
class Date{

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


};

Interfaces in Date.h
class Date{

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

};

9
Constructors and Destructors in
Date.h
Date(int aDay = 0,
int aMonth=
aMonth= 0, int aYear=
aYear= 0);

~Date(); //Destructor
};

Implementation of Date Class

► The static member variables must be


initialized

Date Date::defaultDate (07,3,2005);

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

Destructor
► We are not required to do any house
keeping chores in destructor

Date::~Date
{
}

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

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

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

}

Recap

14
Object-Oriented Programming
(OOP)
Lecture No. 14

Composition
Consider the following implementation
of the student class:
Student
gpa : float
rollNo : int
name : char *

Student(char * = NULL, int = 0,


float = 0.0);
Student(const Student &)
GetName() const : const char *
SetName(char *) : void
~Student()

Composition
class Student{
private:
float gpa;
char * name;
int rollNumber;
public:
Student(char * = NULL, int = 0,
float = 0.0);
Student(const Student & st);
const char * GetName() const;
~Student();

};

Composition
Student::Student(char * _name, int roll,
float g){
cout << "Constructor::Student..\
"Constructor::Student..\n";
if (!_name){
name = new char[strlen(_name)+1];
strcpy(name,_name);
}
else name = NULL;
rollNumber = roll;
gpa = g;
}
Composition
Student::Student(const Student & st){
if(str.name != NULL){
name = new char[strlen(st.name) + 1];
strcpy(name, st.name);
}
else name = NULL;
rollNumber = st.roll;
gpa = st.g;
}

Composition
const char * Student::GetName(){
return name;
}

Student::~Student(){
delete [] name;
}
Composition
►C++: “its all about code reuse”
►Composition:
ƒCreating objects of one class inside
another class
►“Has a” relationship:
ƒBird has a beak
ƒStudent has a name

Composition
Conceptual notation:

Student
gpa : float
rollNo : int String
name : String string : char *
Student(char * = NULL, int = 0,
float = 0.0); String()
Student(const Student &) SetString(char *) : void
GetName() const : String GetString() const : const char *
GetNamePtr() const : const char * ~String()
SetName(char *) : void …
~Student()

Composition
class String{
private:
char * ptr;
public:
String();
String(const String &);
void SetString(char *);
const char * GetString() const;
~String()

};

Composition
String::String(){
cout << "Constructor::String..\
"Constructor::String..\n";
ptr = NULL;
}

String::String(const String & str){


if(str.ptr != NULL){
string = new
char[strlen(str.ptr)+1];
strcpy(ptr, str.ptr);
}
else ptr = NULL;
}
Composition
void String::SetString(char * str){
if(ptr != NULL){
delete [] ptr;
ptr = NULL;
}
if(str != NULL){
ptr = new
char[strlen(str)+1];
strcpy(ptr, str);
}
}

Composition
const char * String::GetString()const{
return ptr;
}
String::~String(){
delete [] ptr;
cout <<"Destructor::String..\
<<"Destructor::String..\n";
}
Composition
class Student{
private:
float gpa;
int rollNumber;
String name;
public:
Student(char* =NULL, int=0,float=0.0);
Student(const Student &);
void SetName(const char *);
String GetName() const;
const char * GetNamePtr const();
~Student();

};

Composition
Student Student(char * _name,
int roll, float g){
cout <<"Constructor::Student..\
<<"Constructor::Student..\n";
name.SetString(_name);
rollNumber = roll;
gpa = g;
}
Composition
Student::Student(const Student & s){
name.Setname(s.name.GetString());
gpa = s.gpa;
rollNo = s.rollNo;
}

const char * Student::GetNamePtr() const{


return name.GetString();
}

Composition
void Student::SetName(const char * n){
name.SetString(n);
}

Student::~Student(){
cout <<"Destructor::Student..\
<<"Destructor::Student..\n";
}
Composition
Main Function:

void main(){
Student aStudent("Fakhir", 899,
3.1);
cout << endl;
cout << “Name:”
Name:”
<< aStudent.GetNamePtr()
<< “\n”;
}

Composition
►Output:
Constructor::String..
Constructor::Student..

Name: Fakhir
Destructor::Student..
Destructor::String..
Composition
►Constructors of the sub-objects
are always executed before the
constructors of the master class

►Example:
ƒConstructor for the sub-object
name is executed before the
constructor of Student
Object-Oriented Programming
(OOP)
Lecture No. 15

Composition
Conceptual notation:

Student
gpa : float
rollNo : int String
name : String string : char *
Student(char * = NULL, int = 0,
float = 0.0); String()
Student(const Student &) SetString(char *) : void
GetName() const : String GetString() const : const char *
GetNamePtr() const : const char * ~String()
SetName(char *) : void …
~Student()

Composition
Main Function:

int main(){
Student aStudent("Fakhir", 899,
3.1);
cout << endl;
cout << “Name:”
Name:”
<< aStudent.GetNamePtr()
<< endl;
return 0;
}

Composition
►Output:
Constructor::String..
Constructor::Student..

Name: Fakhir
Destructor::Student..
Destructor::String..
Composition
Student::Student(char * n,
int roll, float g){
cout <<"Constructor::
Student..\n";
name.SetString(n);
rollNumber = roll;
gpa = g;
}

Composition
►To assign meaningful values to the
object, the function SetString is called
explicitly in the constructor
►This is an overhead
►Sub-object name in the student class
can be initialized using the constructor
►“Member initialization list” syntax is used
Composition
►Add an overloaded constructor to the
String class defined above:

class String{
char *ptr;
public:
String(); //String(char * = NULL);
String(char *);
String(const String &);
void SetName(char *);
~String();

};

Composition
String::String(char * str){
if(str != NULL){
ptr = new char[strlen(str)+1];
strcpy(ptr, str);
}
else ptr = NULL;
cout << "Overloaded
Constructor::String..\
Constructor::String..\n";
}
Composition
►Student class is modified as
follows:
class Student{
private:
float gpa;
int rollNumber;
String name;
public:

Student(char *=NULL, int=0, float=0.0);
};

Composition
►Student class
continued:
Student::Student(char * n,int roll,
float g): name(n){
name(n){
cout << "Constructor::Student..\
"Constructor::Student..\n";
rollNumber = roll;
gpa = g;
}
Composition
Main Function:

int main(){
Student aStudent("Fakhir", 899,
3.1);
cout << endl;
cout << “Name:”
Name:”
<< aStudent.GetNamePtr()
<< endl;
return 0;
}

Composition
►Output:
Overloaded Constructor::String..
Constructor::Student..

Name: Fakhir
Destructor::Student..
Destructor::String..
Composition
Now consider the following case:
String
name: char *
Student
String()
… String(char *)
name : String ~String()
birthDate : Date …

Student()
Student( char *, Date
const Date &, int, float)
SetName(char *) : void day: int
GetName() : char * Month: int
~Student() year: int
… …
Date()
Date(int,int,int)
Date(const Date &)

Composition
►Student class is modified as
follows:
class Student{
private:

Date birthDate;
String name;
public:
Student(char *, const Date &, int,
float);
~Student();

};
Composition
►Student class continued:
Student::Student(char * n, const Date & d,
int roll, flaot g): name(n),birthDate(d){
name(n),birthDate(d){
cout << "Constructor::Student..\
"Constructor::Student..\n";
rollNumber = roll;
gpa = g;
}

Student::~Student(){
cout << "Destructor::Student..\
"Destructor::Student..\n";
}

Composition
►Main function:

int main(){
Date _date(31, 12, 1982);
Student aStudent("Fakhir",
_date,899,3.5);
return 0;
}
Composition
►Output:

Overloaded Constructor::Date..
Copy Constructor::Date..
Overloaded Constructor::String..
Constructor::Student..
Destructor::Student..
Destructor::String..
Destructor::Date..
Destructor::Date..

Aggregation
Composition vs. Aggregation
►Aggregation is a weak relationship

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

Aggregation
►In aggregation, a pointer or
reference to an object is created
inside a class
►The sub-object has a life that is
NOT dependant on the life of its
master class
►e.g:
ƒChairs can be moved inside or outside at
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]-
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
►Butfriend functions are NOT
member functions

Friend Functions
►Friend functions can be placed anywhere in the
class without any effect
►Access specifiers don’
don’t affect friend functions or
classes
class X{
...
private:
friend void DoSomething(X);
public:
friend void DoAnything(X);
...
};
Friend Functions
►While the definition of the friend function
is:

void DoSomething(X obj){


obj.a = 3; // No Error
obj.b = 4; // No Error

}
►friend keyword is not given in definition

Friend Functions
►If keyword friend is used in the
function definition, it’s a syntax error

//Error…
//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;
}
Object-Oriented Programming
(OOP)
Lecture No. 16

Operator overloading
►Consider the following class:
class Complex{
private:
double real, img;
public:
Complex Add(const Complex &);
Complex Subtract(const Complex &);
Complex Multiply(const Complex &);

}
Operator overloading
►Function
implementation:
Complex Complex::Add(
const Complex & c1){
Complex t;
t.real = real + c1.real;
t.img = img + c1.img;
return t;
}

Operator overloading

►The following statement:


Complex c3 = c1.Add(c2);
Adds the contents of c2 to c1 and
assigns it to c3 (copy constructor)
Operator overloading
►To perform operations in a
single mathematical statement
e.g:
c1+c2+c3+c4

►We have to explicitly write:


c1.Add(c2.Add(c3.Add(c4)))

Operator overloading

►Alternative way is:


t1 = c3.Add(c4);
t2 = c2.Add(t1);
t3 = c1.Add(t2);
Operator overloading
►If the mathematical expression is
big:
ƒConverting it to C++ code will involve
complicated mixture of function calls
ƒLess readable
ƒChances of human mistakes are very
high
ƒCode produced is very hard to maintain

Operator overloading
►C++ provides a very elegant
solution:
“Operator overloading”
►C++ allows you to overload
common operators like +, - or * etc…
►Mathematical statements don’t have
to be explicitly converted into function
calls
Operator overloading

►Assume that operator + has been


overloaded
►ActualC++ code becomes:
c1+c2+c3+c4
►The resultant code is very easy
to read, write and maintain

Operator overloading
►C++ automatically overloads
operators for pre-defined types
►Example of predefined types:
int
float
double
char
long
Operator overloading

►Example:
float x;
int y;
x = 102.02 + 0.09;
Y = 50 + 47;

Operator overloading
The compiler probably calls the correct
overloaded low level function for addition
i.e:
// for integer addition:
Add(int a, int b)

// for float addition:


Add(float a, float b)
Operator overloading

►Operator functions are not usually


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

Operator overloading
►List of operators that can be
overloaded in C++:
Operator overloading
►List of operators that can’t be
overloaded:

►Reason: They take name, rather


than value in their argument except
for ?:
►?: is the only ternary operator in
C++ and can’t be overloaded

Operator overloading
►The precedence of an operator
is NOT affected due to
overloading
►Example:
c1*c2+c3
c3+c2*c1
both yield the same answer
Operator overloading

►Associativityis NOT changed


due to overloading
►Following arithmetic expression
always is evaluated from left to
right:
c1 + c2 + c3 + c4

Operator overloading

►Unary operators and assignment


operator are right associative, e.g:
a=b=c is same as a=(b=c)
►Allother operators are left
associative:
c1+c2+c3 is same as
(c1+c2)+c3
Operator overloading

►Always write code representing


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

Operator overloading

►Creating a new operator is a syntax


error (whether unary, binary or
ternary)
► You cannot create $
Operator overloading

►Arity of an operator is NOT affected


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

Binary operators
►Binary operators act on two
quantities
►Binary operators:
Binary operators

►General syntax:
Member function:
TYPE1 CLASS::operator B_OP(
TYPE2 rhs){
...
}

Binary operators

►General syntax:
Non-member function:
TYPE1 operator B_OP(TYPE2 lhs,
TYPE3 rhs){
...
}
Binary operators

►The “operator OP” must have at


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

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

Complex operator +(const
Complex & rhs);
};
Binary operators
Complex Complex::operator +(
const Complex & rhs){
Complex t;
t.real = real + rhs.real;
t.img = img + rhs.img;
return t;
}

Binary operators
►The return type is Complex so as to
facilitate complex statements like:
Complex t = c1 + c2 + c3;
►The above statement is
automatically converted by the
compiler into appropriate function
calls:
(c1.operator +(c2)).operator
+(c3);
Binary operators

►If the return type was void,


class Complex{
...
public:
void operator+(
const Complex & rhs);
};

Binary operators

void Complex::operator+(const
Complex & rhs){
real = real + rhs.real;
img = img + rhs.img;
};
Binary operators

►we have to do the same operation


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

Binary operators

►Drawback of void return type:


ƒAssignments and cascaded expressions
are not possible
ƒCode is less readable
ƒDebugging is tough
ƒCode is very hard to maintain
Object-Oriented Programming
(OOP)
Lecture No. 17

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

Complex operator +(const
Complex & rhs);
};
Binary operators
Complex Complex::operator +(
const Complex & rhs){
Complex t;
t.real = real + rhs.real;
t.img = img + rhs.img;
return t;
}

Binary operators
►The return type is Complex so as to
facilitate complex statements like:
Complex t = c1 + c2 + c3;
►The above statement is
automatically converted by the
compiler into appropriate function
calls:
(c1.operator +(c2)).operator
+(c3);
Binary operators

►The binary operator is always called


with reference to the left hand
argument
►Example:

ƒIn c1+c2, c1.operator+(c2)


ƒIn c2+c1, c2.operator+(c1)

Binary operators
►The above examples don’t
handle the following situation:
Complex c1;
c1 + 2.325

►To do this, we have to modify


the Complex class
Binary operators
►Modifying the complex class:
class Complex{
...
Complex operator+(const
Complex & rhs);
Complex operator+(const
double& rhs);
};

Binary operators
Complex operator + (const double&
rhs){
Complex t;
t.real = real + rhs;
t.img = img;
return t;
}
Binary operators
►Now suppose:
Complex c2, c3;

►We can do the following:


Complex c1 = c2 + c3;
and
Complex c4 = c2 + 235.01;

Binary operators

►But problem arises if we do the following:


Complex c5 = 450.120 + c1;

►The + operator is called with reference to


450.120

►No predefined overloaded + operator is


there that takes Complex as an argument
Binary operators
►Now if we write the following two
functions to the class, we can add a
Complex to a real or vice versa:
Class Complex{

friend Complex operator + (const
Complex & lhs, const double & rhs);
rhs);
friend Complex operator + (const
double & lhs,
lhs, const Complex & rhs);
}

Binary operators
Complex operator +(const Complex &
lhs, const double& rhs){

Complex t;
t.real = lhs.real + rhs;
t.img = lhs.img;
return t;
}
Binary operators
Complex operator + (const double &
lhs, const Complex & rhs){

Complex t;
t.real = lhs + rhs.real;
t.img = rhs.img;
return t;
}

Binary operators
Class Complex{

Complex operator + (const
Complex &);
friend Complex operator + (const
Complex &, const double &);
friend Complex operator + (const
double &, const Complex &);
};
Binary operators
►Other binary operators are overloaded
very similar to the + operator as
demonstrated in the above examples
►Example:
Complex operator * (const Complex &
c1, const Complex & c2);
Complex operator / (const Complex &
c1, const Complex & c2);
Complex operator - (const Complex &
c1, const Complex & c2);

Assignment operator
►Consider a string class:
class String{
int size;
char * bufferPtr;
public:
String();
String(char *);
String(const String &);

};
Assignment operator

String::String(char * ptr){
if(ptr != NULL){
size = strlen(ptr);
bufferPtr = new char[size+1];
strcpy(bufferPtr, ptr);
}
else{
bufferPtr = NULL; size = 0; }
}

Assignment operator

String::String(const String & rhs){


size = rhs.size;
if(rhs.size != 0){
bufferPtr = new char[size+1];
strcpy(bufferPtr, ptr);
}
else
bufferPtr = NULL;
}
Assignment operator

int main(){
String str1(“Hello");
String str2(“World”);
str1 = str2;
Member wise
return 0; copy assignment
}

Assignment operator

►Result of str1 = str2 (memory leak)

Hello World

str1 str2
Assignment operator

►Modifying:
class String{

public:

void operator =(const String &);
};

Assignment operator
void String::operator = (const String & rhs){
size = rhs.size;
if(rhs.size != 0){
delete [] bufferPtr;
bufferPtr = new char[rhs.size+1];
strcpy(bufferPtr,rhs.bufferPtr);
}
else
bufferPtr = NULL;
}
Assignment operator

int main(){
String str1(“ABC");
String str2(“DE”), str3(“FG”);
str1 = str2; // Valid…
str1 = str2 = str3; // Error…
return 0;
}

Assignment operator
►str1=str2=str3 is resolved as:
str1.operator=(str2.operator=
(str3))

Return type is
void. Parameter
can’t be void
Object-Oriented Programming
(OOP)
Lecture No. 18

Assignment operator

►Modifying:
class String{

public:

void operator =(const String &);
};
Assignment operator
void String::operator = (const String & rhs){
size = rhs.size;
delete [] bufferPtr;
if(rhs.size != 0){
bufferPtr = new char[rhs.size+1];
strcpy(bufferPtr,rhs.bufferPtr);
}
else
bufferPtr = NULL;
}

Assignment operator

int main(){
String str1(“ABC");
String str2(“DE”), str3(“FG”);
str1 = str2; // Valid…
str1 = str2 = str3; // Error…
return 0;
}
Assignment operator
►str1=str2=str3 is resolved as:

str1.operator=(str2.operator=
(str3))
Return type is
void. Parameter
can’t be void

Assignment operator
►Solution: modify the operator =
function as follows:
class String{

public:

String & operator = (const
String &);
};
Assignment operator
String & String :: operator = (const String &
rhs){
size = rhs.size;
delete [] bufferPtr;
if(rhs.size != 0){
bufferPtr = new char[rhs.size+1];
strcpy(bufferPtr,rhs.bufferPtr);
}
else bufferPtr = NULL;
return *this;
}

Assignment operator

void main(){
String str1(“
str1(“AB");
String str2(“
str2(“CD”
CD”), str3(“
str3(“EF”
EF”);
str1 = str2;
str1 = str2 = str3; // Now valid…
valid…
}
Assignment operator
►str1=str2=str3 is resolved as:

str1.operator=(str2.operator=
(str3))
Return type is
String .

Assignment operator

int main(){
String str1("Fakhir");
// Self Assignment problem…
str1 = str1;
return 0;
}
Assignment operator

►Result of str1 = str1



// size = rhs.size;
??? // delete [] bufferPtr;
Fakhir …

str1

Assignment operator
String & String :: operator = (const
String & rhs){
if(this != &rhs){
size = rhs.size;
delete [] bufferPtr;
if(rhs.bufferPtr != NULL){
bufferPtr = new char[rhs.size+1];
strcpy(bufferPtr,rhs.bufferPtr);
}
else bufferPtr = NULL;
}
return *this; }
Assignment operator

►Now self-assignment is properly handled:

int main(){
String str1("Fakhir");
str1 = str1;
return 0;
}

Assignment operator
►Solution: modify the operator=
function as follows:
class String{

public:

const String & operator=
(const String &);
};
Assignment operator
int main(){
String s1(“
s1(“ABC”
ABC”),
s2(“
s2(“DEF”
DEF”),
s3(“
s3(“GHI”
GHI”);
// Error…
Error…
(s1 = s2) = s3;
return 0;
}

Assignment operator
But we can do the following with
primitive types:
int main(){
int a, b, c;
(a = b) = c;
return 0;
}
Other Binary operators
►Overloading += operator:
class Complex{
double real, img;
public:
Complex & operator+=(const Complex &
rhs);
Complex & operator+=(count double &
rhs);
...
};

Other Binary operators

Complex & Complex::operator +=


(const Complex & rhs){
real = real + rhs.real;
img = img + rhs.img;
return * this;
}
Other Binary operators

Complex & Complex::operator +=


(const double & rhs){
real = real + rhs;
return * this;
}

Other Binary operators

int main(){
Complex c1, c2, c3;
c1 += c2;
c3 += 0.087;
return 0;
}
Operator overloading
►Friend functions minimize
encapsulation
►This can result in:
ƒData vulnerability
ƒProgramming bugs
ƒTough debugging
►Hence, use of friend functions must
be limited

Operator overloading
►The + operator can be defined as a
non-member, non-friend function:

Complex operator + (const Complex &


a, const Complex & b){
Complex t = a;
return t += b
}
Operator overloading

Complex operator + (const double &


a, const Complex & b){
Complex t = b;
return t += a;
}

Operator overloading

Complex operator + (const Complex &


a, const double & b){
Complex t = a;
return t += b;
}
Other Binary operators
The operators
-=, /=, *=, |=, %=, &=, ^=,
<<=, >>=, !=

can be overloaded in a very


similar fashion
Object-Oriented Programming
(OOP)
Lecture No. 19

Stream Insertion operator

►Often we need to display the data


on the screen
►Example:
int i=1, j=2;
cout << “i= ”<< i << “\n”;
Cout << “j= ”<< j << “\n”;
Stream Insertion operator

Complex c1;
cout << c1;
cout << c1 << 2;

// Compiler error: binary '<<' : no


operator // defined which takes a right-
hand // operand of type ‘class
Complex’

Stream Insertion operator

class Complex{

public:

void operator << (const
Complex & rhs);
};
Stream Insertion operator

int main(){
Complex c1;
cout << c1; // Error
c1 << cout;
c1 << cout << 2; // Error
return 0;
};

Stream Insertion operator

class Complex{

public:

void operator << (ostream &);
};
Stream Insertion operator

void Complex::operator <<


(ostream & os){
os << ‘(‘ << real
<< ‘,’ << img << ‘)’;
}

Stream Insertion operator


class Complex{
Note: return type
... is NOT const

friend ostream & operator <<


(ostream & os, const Complex
& c);
}; Note: this object
is NOT const
Stream Insertion operator

// we want the output as: (real, img)


ostream & operator << (ostream &
os, const Complex & c){
os << ‘(‘ << c.real
<< ‘,‘
<< c.img << ‘)’;
return os;
}

Stream Insertion operator

Complex c1(1.01, 20.1),


c2(0.01, 12.0);

cout << c1 << endl << c2;


Stream Insertion operator

Output:
( 1.01 , 20.1 )
( 0.01 , 12.0 )

Stream Insertion operator

cout << c1 << c2;

is equivalent to

operator<<(
operator<<(cout,c1),c2);
operator<<(cout,c1),c2);
Stream Extraction Operator
►Overloading “>>” operator:
class Complex{
...
friend istream & operator
>> (istream & i, Complex &
c);
Note: this object
}; is NOT const

Stream Extraction Operator

istream & operator << (istream


& in, Complex & c){
in >> c.real;
in >> c.img;
return in;
}
Stream Extraction Operator
►Main Program:
Complex c1(1.01, 20.1);
cin >> c1;
// suppose we entered
// 1.0025 for c1.real and
// 0.0241 for c1.img
cout << c1;

Stream Extraction Operator

Output:
( 1.0025 , 0.0241 )
Other Binary operators
►Overloading comparison operators:
class Complex{
public:
bool operator == (const Complex & c);
//friend bool operator == (const
//Complex & c1, const Complex & c2);
bool operator != (const Complex & c);
//friend bool operator != (const
//Complex & c1, const Complex & c2);

};

Other Binary operators


bool Complex::operator ==(const
Complex & c){
if(
if((real == c.real) &&
(img == c.img))
c.img)){
return true;
}
else
return false;
}
Other Binary operators
bool operator ==(const
Complex& lhs, const Complex& rhs){
if(
if((lhs.real == rhs.real) &&
(lhs.img == rhs.img))
rhs.img)){
return true;
}
else
return false;
}

Other Binary operators


bool Complex::operator !=(const
Complex & c){
if(
if((real != c.real) ||
(img != c.img))
c.img)){
return true;
}
else
return false;
}
Object-Oriented Programming
(OOP)
Lecture No. 20

Other Binary operators


►We have seen the following string class till now:
class String{
private:
char * bufferPtr; int size;
public:
String();
String(char * ptr);
void SetString(char * ptr);
const char * GetString();
...
};
Other Binary Operators
int main(){
String str1(“Test”);
String str2;
str2.SetString(“Ping”);
return 0;
}

Other Binary Operators


►What if we want to change the string
from “Ping” to “Pong”?? {ONLY 1
character to be changed…}
►Possible solution:
ƒCall: str2.SetString(“Pong”);
ƒThis will delete the current buffer and
allocate a new one
ƒToo much overhead if string is too big
Other Binary Operators
►Or, we can add a function which
changes a character at nth location
class String{
...
public:
void SetChar(char c, int pos);
...
};

Other Binary Operators


void SetChar(char c, int pos){
if(bufferPtr != NULL){
if(pos>0 && pos<=size)
bufferPtr[pos] = c;
}
}
Other Binary Operators

►Now we can efficiently change a


single character:
String str1(“Ping”);
str1.SetChar(‘o’, 2);
// str1 is now changed to “Pong”

Subscript Operator

►An elegant solution:

►Overloading the subscript “[]”


operator
Subscript Operator
int main(){
String str2;
str2.SetString(“Ping”);
str[2] = ‘o’;
cout << str[2];
return 0;
}

Subscript Operator
class String{
...
public:
char & operator[](int);
...
};
Subscript Operator
char & String::operator[](
int pos){
assert(pos>0 && pos<=size);
return stringPtr[pos-1];
}

Subscript Operator
int main() {
String s1(“Ping”);
cout <<str.GetString()<< endl;
s1[2] = ‘o’;
cout << str.GetString();
return 0;
}
Subscript Operator

►Output:
Ping
Pong

Overloading ()
►Must be a member function

►Any number of parameters can be specified

►Any return type can be specified

►Operator() can perform any generic


operation
Function Operator
class String{
...
public:
char & operator()(int);
...
};

Function Operator
char & String::operator()
(int pos){
assert(pos>0 && pos<=size);
return bufferPtr[pos-1];
}
Subscript Operator
int main(){
String s1(“
s1(“Ping”
Ping”);
char g = s1(2);
s1(2); // g = ‘i’
s1(2) = ‘o’;
cout << g << “\n”;
cout << str.GetString();
return 0;

Function Operator

►Output:
i
Pong
Function Operator
class String{
...
public:
String operator()(int, int);
...
};

Function Operator
String String::operator()(int index,
int subLength){
assert(index>0 && index+subLength-
index+subLength-1<=size);
char * ptr = new char[subLength+1];
for (int i=0; i < subLength; ++i)
ptr[i] = bufferPtr[i+index-
bufferPtr[i+index-1];
ptr[subLength] = ‘\0’;
String str(ptr);
delete [] ptr;
return str;
}
Function Operator
int main(){
String s(“Hello World”);
// “<<“ is overloaded
cout << s(1, 5);
return 0;
}

Function Operator

Output:
Hello
Unary Operators
►Unary operators:
ƒ & * + - ++ -- ! ~
►Examples:
--x
-(x++)
!(*ptr ++)

Unary Operators
►Unary operators are usually
prefix, except for ++ and --
►++ and -- both act as prefix
and postfix
►Example:
h++;
g-- + ++h - --i;
Unary Operators
►General syntax for unary
operators:
Member Functions:
TYPE & operator OP ();
Non-member Functions:
Friend TYPE & operator OP
(TYPE & t);

Unary Operators
►Overloading unary ‘-’:
class Complex{
...
Complex operator - ();
// friend Complex operator
// -(Complex &);
}
Unary Operators
►Member function definition:
Complex Complex::operator -(){
Complex temp;
temp.real = -real;
temp.img = -img;
return temp;
}

Unary Operators
Complex c1(1.0 , 2.0), c2;
c2 = -c1;
// c2.real = -1.0
// c2.img = -2.0

►Unary ‘+’ is overloaded in the same


way
Object-Oriented Programming
(OOP)
Lecture No. 21

Unary Operators
►Unary operators are usually prefix,
except for ++ and --
►++ and -- both act as prefix and
postfix
►Example:
ƒ h++;
ƒ g-- + ++h - --i;
Unary Operators
►Behavior of ++ and -- for pre-
defined types:
ƒPost-increment ++:
►Post-increment operator ++
increments the current value and then
returns the previous value
ƒPost-decrement --:
►Works exactly like post ++

Unary Operators
►Example:
int x = 1, y = 2;
cout << y++ << endl;
cout << y;

►Output:
2
3
Unary Operators
►Example:
int y = 2;
y++++; // Error
y++ = x; // Error

Post-increment ++
returns by value,
hence an error while
assignment

Unary Operators
►Behavior of ++ and -- for pre-
defined types:
ƒPre-increment ++:
►Pre-
Pre-increment operator ++ increments
the current value and then returns it’
it’s
reference

ƒPre-decrement --:
►Works exactly like Pre-
Pre-increment ++
Unary Operators
►Example:
int y = 2;
cout << ++y << endl;
cout << y << endl;

►Output:
3
3

Unary Operators
►Example:
int x = 2, y = 2;
++++y;
cout << y;
++y = x;
Pre-increment ++
cout << y; returns by
reference, hence
►Output: NOT an error

4
2
Unary Operators

►Example (Pre-increment):
class Complex{
double real, img;
public:
...
Complex & operator ++ ();
// friend Complex & operator
// ++(Complex &);
}

Unary Operators

►Member function definition:

Complex & Complex::operator++(){


real = real + 1;
return * this;
}
Unary Operators

►Friend function definition:

Complex & operator ++ (Complex


& h){
h.real += 1;
return h;
}

Unary Operators
Complex h1, h2, h3;
++h1;
►Function operator++() returns a
reference so that the object can be
used as an lvalue
++h1 = h2 + ++h3;
Unary Operators

►How does a compiler know


whether it is a pre-increment
or a post-increment ?

Unary Operators
►A post-fix unary operator is
implemented using:
Member function with 1 dummy int
argument
OR
Non-member function with two
arguments
Unary Operators
►In post increment, current value of
the object is stored in a temporary
variable
►Current object is incremented
►Value of the temporary variable is
returned

Unary Operators
►Post-increment operator:
class Complex{
...
Complex operator ++ (int);
// friend Complex operator
// ++(const Complex &, int);
}
Unary Operators

►Member function definition:


Complex Complex::operator ++
(int){
complex t = *this;
real += 1;
return t;
}

Unary Operators
►Friend function definition:
Complex operator ++ (const
Complex & h, int){
complex t = h;
h.real += 1;
return t;
}
Unary Operators
►The dummy parameter in the
operator function tells compiler that it
is post-increment
►Example:
Complex h1, h2, h3;
h1++;
h3++ = h2 + h3++; // Error…

Unary Operators

►The pre and post decrement


operator -- is implemented in
exactly the same way
Type Conversion
►The compiler automatically performs
a type coercion of compatible types
►e.g:
int f = 0.021;
double g = 34;
// type float is automatically converted
// into int. Compiler only issues a
// warning…

Type Conversion
►The user can also explicitly convert
between types:
C style type
casting

int g = (int)0.0210;
double h = double(35);
// type float is explicitly converted
// (casted) into int. Not even a warning
// is issued now…
Type Conversion

►For user defined classes, there are


two types of conversions
ƒFrom any other type to current type
ƒFrom current type to any other type

Type Conversion

►Conversion from any other type to


current type:
ƒRequires a constructor with a single
parameter

►Conversion from current type to any


other type:
ƒRequires an overloaded operator
Type Conversion
►Conversion from other type to
current type (int to String):

class String{
...
public:
String(int a);
char * GetStringPtr()const;
};

Type Conversion
String::String(int a){
cout << "String(int) called..." << endl;
char array[15];
itoa(a, array, 10);
size = strlen(array);
bufferPtr = new char [size + 1];
strcpy(bufferPtr, array);
}

char * String::GetStringPtr() const{


return bufferPtr;
}
Type Conversion

int main(){
String s = 345;
cout << s.GetStringPtr() << endl;
return 0;
}

Type Conversion

►Output:
String(int) called…
345
Type Conversion
►Automatic conversion has
drawbacks
►Conversion takes place
transparently even if the user didn’t
wanted the conversion

Type Conversion
User can write the following code to initialize
the string with a single character:

int main(){
String s = ‘A’;
cout << s.GetStringPtr()<< endl
<< s.GetSize() << endl;
return 0;
}
Type Conversion

►Output:
String(int) called…
65 ASCII code
for ‘A’ !!!
2
String size
is also 2
instead of 1

Type Conversion

There is a mechanism in C++ to


restrict automatic conversions
►Keyword explicit
►Casting must be explicitly performed
by the user
Type Conversion
►Keyword explicit only works
with constructors
►Example:
class String{

public:

explicit String(int);
};

Type Conversion

int main(){
String s;
// Error…
s = ‘A’;
return 0;
}
Type Conversion

int main(){
String s1, s2;
// valid, explicit casting…
casting…
s1 = String(101);
// OR
s2 = (String)204;
return 0;
}

Type Conversion

►There is another method for type


conversion:
“Operator overloading”

(Converting from current type to


any other type)
Type Conversion
►General Syntax:
TYPE1::Operator TYPE2();

►Must be a member function


►NO return type and arguments are
specified
►Return type is implicitly taken to be
TYPE2 by compiler

Type Conversion
►Overloading pre-defined types:
class String{

public:

operator int();
operator char *();
};
Type Conversion

String::operator int(){
if(size > 0)
return atoi(bufferPtr);
else
return -1;
}

Type Conversion

String::operator char *(){


return bufferPtr;
}
Type Conversion

int main(){
String s("2324");
cout << (int)s << endl
<< (char *)s;
return 0;
}

Type Conversion

Output:
2324
2324
Type Conversion
►User-defined types can be overloaded
in exactly the same way
►Only prototype is shown below:
class String{

operator Complex();
operator HugeInt();
operator IntVector();
};

Type Conversion
►Modifying String class:
class String{

public:

String(char *);
operator int();
};
Type Conversion

int main(){
String s(“Fakhir");
// << is NOT overloaded
cout << s;
return 0;
}

Type Conversion

Output:
Junk Returned…
Type Conversion
►Modifying String class:
class String{

public:

String(char *);
int AsInt();
};

Type Conversion

int String::AsInt(){
if(size > 0)
return atoi(bufferPtr);
else
return -1;
}
Type Conversion

int main(){
String s(“434");
// << is NOT overloaded
cout << s; //error
cout << s.AsInt();
return 0;
}
Object-Oriented Programming
(OOP)
Lecture No. 22

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

Parent Class Base Class

Child Class Derived Class

Inheritance in C++

► There are three types of inheritance in C++

ƒ Public
ƒ Private
ƒ Protected
“IS A” Relationship
► IS
A relationship is modeled with the help of
public inheritance

► Syntax
class ChildClass
: public BaseClass{
...
};

Example
class Person{
...
};
class Student: public Person{
...
};
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)

Example
class Person{
char *name;
int age;
...
public:
const char *GetName() const;
int GetAge() const;
...
};
Example
class Student: public Person{
int semester;
int rollNo;
...
public:
int GetSemester() const;
int GetRollNo() const;
void Print() const;
...
};

Example

void Student::Print()
{ ERROR
cout << name << “ is in” << “
semester ” << semester;
}
Example

void Student::Print()
{
cout << GetName()
<< “ is in semester ”
<< semester;
}

Example
int main(){
Student stdt;

stdt.semester = 0;//error
stdt.name = NULL; //error
cout << stdt.GetSemester();
cout << stdt.GetName();
return 0;
}
Allocation in Memory
► Theobject 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
...

Allocation in Memory
► Every
object of derived class has an
anonymous object of base class
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

Constructors

base member1 Base class constructor


base member2 initializes the anonymous
... object
derived member1 Derived class constructor
derived member2 initializes the derived
... class object
Example
class Parent{
public:
Parent(){ cout <<
“Parent Constructor...”;}
};
class Child : public Parent{
public:
Child(){ cout <<
“Child Constructor...”;}
};

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

Output:
Parent Constructor...
Child Constructor...
Constructor
► If default constructor of base class does
not exist then the compiler will try to
generate a default constructor for base
class and execute it before executing
constructor of derived class

Constructor
► Ifthe user has given only an overloaded
constructor for base class, the compiler
will not generate default constructor for
base class
Example
class Parent{
public:
Parent(int i){}
};
class Child : public Parent{
public:
Child(){}
} Child_Object; //ERROR

Base Class Initializer


► C++ has provided a mechanism to
explicitly call a constructor of base class
from derived class

► Thesyntax is similar to member initializer


and is referred as base-class initialization
Example
class Parent{
public:
Parent(int i){…};
};
class Child : public Parent{
public:
Child(int i): Parent(i)
{…}
};

Example
class Parent{
public:
Parent(){cout <<
“Parent Constructor...”
Constructor...”;}
...
};
class Child : public Parent{
public:
Child():Parent
Child():Parent()
()
{cout << “Child Constructor...”
Constructor...”;}
...
};
Base Class Initializer
► User
can provide base class initializer and
member initializer simultaneously

Example
class Parent{
public:
Parent(){…}
};
class Child : public Parent{
int member;
public:
Child():member(0), Parent()
{…}
};
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.

Initializing Members
► Derivedclass can only initialize members
of base class using overloaded
constructors
ƒ Derived class can not initialize the public data
member of base class using member
initialization list
Example
class Person{
public:
int age;
char *name;
...
public:
Person();
};

Example
class Student: public Person{
private:
int semester;
...
public:
Student(int a):age(a)
{ //error
}
};
Reason
► It will be an assignment not an initialization

Destructors

► Destructors are called in reverse order of


constructor called
► Derived class destructor is called before the
base class destructor is called
Example
class Parent{
public:
Parent(){cout <<“
<<“Parent Constructor”
Constructor”;}
~Parent(){cout<<
Parent(){cout<<“
“Parent Destructor”
Destructor”;}
};

class Child : public Parent{


public:
Child(){cout << “Child Constructor”
Constructor”;}
~Child(){cout << “Child Destructo”
Destructo”;}
};

Example
Output:

Parent Constructor
Child Constructor
Child Destructor
Parent Destructor

You might also like