Lecture01-22
Lecture01-22
(OOP)
Lecture No. 1
Course Objective
► 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
2
Grading Policy
► Assignments 15 %
► Group Discussion 5%
► Mid-Term 35 %
► Final 45 %
Object-Orientation (OO)
3
What is Object-Orientation?
What is a Model?
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
6
What is an Object?
An object is
… 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
► 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
9
Object-Oriented Programming
(OOP)
Lecture No. 2
Information Hiding
1
Example – Information Hiding
2
Information Hiding
Advantages
► Simplifies
the model by hiding
implementation details
Encapsulation
3
Example – Encapsulation
► 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
► Low complexity
► Better understanding
5
Example – Interface of a Car
► Steer Wheels
► Accelerate
► Change Gear
► Apply Brakes
► Turn Lights On/Off
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
8
Example – Separation of
Interface & Implementation
► Because
interface does not change with the
implementation
Example – Separation of
Interface & Implementation
9
Advantages of Separation
► Users need not to worry about a change
until the interface is same
► Low Complexity
Messages
10
Examples – Messages
11
Object-Oriented Programming
(OOP)
Lecture No. 3
Abstraction
► Principle of abstraction:
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
Example – Abstraction
Engineer’s View
Driver’s View
5
Abstraction – Advantages
► Abstraction
provides the freedom to defer
implementation decisions by avoiding
commitment to details
Classes
6
Example – Class
► Ali
studies mathematics
► Anam studies physics
► Sohail studies chemistry
Example – Class
► Ahsan teaches mathematics
► Aamir teaches computer science
► Atif teaches physics
7
Graphical Representation of Classes
(Class Name)
(Class Name)
(attributes)
Suppressed
(operations)
Form
Normal Form
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
► 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
11
Example – “IS A” Relationship
Person
name
age
gender
eat
walk
Circle Triangle
radius Line angle
draw length draw
computeArea draw computeArea
12
Inheritance – Advantages
► Reuse
► Less redundancy
► Increased maintainability
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
14
Example Reuse
Person
name
age
gender
eat
walk
15
Object-Oriented Programming
(OOP)
Lecture No. 4
Recap – Inheritance
► Derivedclass inherits all the characteristics
of the base class
1
Concepts Related with
Inheritance
► Generalization
► Subtyping (extension)
► Specialization (restriction)
Generalization
► In
OO models, some classes may have
common characteristics
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
4
Sub-typing & Specialization
► Wewant to add a new class to an existing
model
► 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
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
Example – Specialization
(Restriction)
Person
age : [0..100]
…
setAge( a ) age = a
…
7
Example – Specialization
(Restriction)
IntegerSet
…
add( elem ) add element
… to the set
Overriding
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
9
Example – Restriction
IntegerSet
…
add( elem ) Add element
… to the set
Circle
radius
draw
rotate
10
Abstract Classes
Student Doctor
Teacher
► Here, Person is an abstract class
11
Example – Abstract Classes
Vehicle
color
model
accelerate
applyBrakes
Car Truck
Bus
Concrete Classes
►A concrete class implements a concrete
concept
► Provides
implementation details specific to
the domain context
12
Example – Concrete Classes
Person
Student Doctor
program Teacher
studyYear
study
heldExam
Vehicle
Car Truck
Bus
capacity
load
unload
13
Object-Oriented Programming
(OOP)
Lecture No. 5
Multiple Inheritance
1
Example – Multiple Inheritance
Mermaid
Woman Fish
Mermaid
2
Example – Multiple Inheritance
Amphibious Vehicle
Vehicle
3
Problems with Multiple
Inheritance
► Increased complexity
► Reduced understanding
► Duplicate features
Woman Fish
eat eat
… …
Mermaid
4
Solution – Override the Common
Feature
Woman Fish
eat eat
… …
Mermaid
eat Invoke eat
operation of
… desired class
5
Solution to Diamond Problem
Association
► Objectsin an object model interact with
each other
6
Kinds of Association
► Class Association
Inheritance
► Object Association
Simple Association
Composition
Aggregation
Simple Association
7
Kinds of Simple Association
► w.r.t navigation
One-way Association
Two-way Association
One-way Association
8
Example – Association
lives-in
Ali House
1 1
Example – Association
drives
Ali Car
1 *
9
Two-way Association
works-for
Employee Company
* 1
10
Example – Two-way Association
friend
Yasir Ali
1 1
Binary Association
11
Example – Binary Association
works-for
Employee Company
* 1
drives
Ali Car
1 *
12
Ternary Association
Student 1
Teacher
*
*
Course
13
Example – Ternary Association
Project * *
Language
1
Person
N-ary Association
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
1
Body
15
Example – Composition of Chair
Back
1
Chair
2 1 4
Arm Seat Leg
Composition is Stronger
16
Example – Composition is
Stronger
Example – Composition is
Stronger
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
1
Cupboard
18
Example – Aggregation
Garden * Plant
Aggregation is Weaker
19
Example – Aggregation is Weaker
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
1
…Class Compatibility
► Derived class is usually a subtype of the
base class
Circle Triangle
radius Line angle
length
draw draw
computeArea draw computeArea
getLength
2
Example – Class Compatibility
File
size
…
open
print
…
Polymorphism
3
Polymorphism in OO Model
Example – Polymorphism
draw Shape
View
draw
4
Example – Polymorphism
print File
Editor
print
Polymorphism – Advantages
► Messagescan be interpreted in different
ways depending upon the receiver class
draw Shape
View
draw
5
Polymorphism – Advantages
► New classes can be added without changing
the existing model
draw Shape
View
draw
Polymorphism – Advantages
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
…Identify Classes
¾ Eliminate irrelevant classes
8
…Identify Classes
¾ Add classes by analyzing requirements
…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
10
… Identify Associations
¾ Verify access paths
… Identify Associations
¾ Verify access paths
11
Object Model – Graphic Editor
n n n
Line n Circle Triangle Group
n
n n
Identify Attributes
¾ Extract properties of the object
From the problem statement
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
n n n
Line n Circle Triangle Group
length radius angle noOfObjects
n
n
n
Identify Operations
¾ Extract verbs connected with an object
14
… Identify Operations
¾ Eliminate irrelevant operations
…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
…Identify Inheritance
¾ By analyzing requirements
18
Refining the Object Model
► Applicationof inheritance demands an
iteration over the whole object model
¾ Share associations
19
…Refining the Object Model
¾ Share attributes
¾ Share operations
20
…Refining the Object Model
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()
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;
5
Object and Class
► Objectis an instantiation of a user defined
type or a class
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);
};
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
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;
}
};
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
…
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
1
Copy Constructor
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
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
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.)
Destructor
7
Destructor (contd.)
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;
}
};
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(), …
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
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;
}
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
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
6
Student.h
class Student{
int rollNo;
public:
void setRollNo(int aRollNo);
int getRollNo();
…
};
Student.cpp
#include “student.h”
7
Driver.cpp
#include “student.h”
int main(){
Student aStudent;
}
8
const Member Functions
Definition:
ReturnVal ClassName::Function() const{
…
}
9
Example
class Student{
public:
int getRollNo() const {
return rollNo;
}
};
const Functions
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
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
}
};
14
Object Oriented Programming
(OOP)
Lecture No. 11
Review
► this
Pointer
► Separation of interface and implementation
► Constant member functions
1
Problem
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*/
}
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
Example
class Student{
…
int rollNo;
public:
…
int getRollNo()const{
return rollNo;
}
};
9
Example
int main(){
const Student aStudent;
int a = aStudent.getRollNo();
}
10
Static Variables
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”
12
Class vs. Instance Variable
►Student s1, s2, s3;
s1(rollNo,…)
class ClassName{
…
static DataType VariableName;
};
13
Defining Static Data Member
DataType ClassName::VariableName;
14
Initializing Static Data Member
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
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”
2
Class vs. Instance Variable
► Student s1, s2, s3;
s1(rollNo,…)
class ClassName{
…
static DataType VariableName;
};
3
Defining Static Data Member
DataType ClassName::VariableName;
4
Initializing Static Data Member
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
Example
int Student::noOfStudents;
is equivalent to
int Student::noOfStudents=0;
6
Accessing Static Data Member
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
9
Example
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
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
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;
}
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;
}
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
};
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 *
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;
}
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;
}
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;
}
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:
Friend Functions
►If keyword friend is used in the
function definition, it’s a syntax error
//Error…
//Error…
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
Operator overloading
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
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)
Operator overloading
►List of operators that can be
overloaded in C++:
Operator overloading
►List of operators that 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
Operator overloading
Operator overloading
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
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
Binary operators
void Complex::operator+(const
Complex & rhs){
real = real + rhs.real;
img = img + rhs.img;
};
Binary operators
Binary operators
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
Binary operators
►The above examples don’t
handle the following situation:
Complex c1;
c1 + 2.325
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;
Binary operators
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
int main(){
String str1(“Hello");
String str2(“World”);
str1 = str2;
Member wise
return 0; copy assignment
}
Assignment operator
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
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
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);
...
};
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:
Operator overloading
Complex c1;
cout << c1;
cout << c1 << 2;
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;
};
class Complex{
…
public:
…
void operator << (ostream &);
};
Stream Insertion operator
Output:
( 1.01 , 20.1 )
( 0.01 , 12.0 )
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
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);
…
};
Subscript Operator
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
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 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
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
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
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
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
Type Conversion
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);
}
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
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
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
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
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
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
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
Example
Output:
Parent Constructor
Child Constructor
Child Destructor
Parent Destructor