Lecture01, Lecture02, Defining Class and Objects
Lecture01, Lecture02, Defining Class and Objects
(OOP)
Lecture No. 1
Course Objective
► Concepts
will be reinforced by their
implementation in C++
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
► Assignments 15 %
► Group Discussion 5%
► Mid-Term 35 %
► Final 45 %
Object-Orientation (OO)
What is Object-Orientation?
► Highway maps
► Architectural models
► Mechanical models
Example – OO Model
…Example – OO Model
► Objects
lives-in
Ali House
▪ Ali
drives
▪ House
▪ Car
Car Tree
▪ Tree
► Interactions
▪ Ali lives in the house
▪ Ali drives the car
Object-Orientation - Advantages
► People think in terms of objects
► State (attributes)
► Well-defined behaviour (operations)
► Unique identity
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
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
Object-Oriented Programming
(OOP)
Lecture No. 2
Information Hiding
► Simplifies
the model by hiding
implementation details
► 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
Encapsulation – Advantages
► Low complexity
► Better understanding
Object has an 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
Example – Implementation of
Address Book in a Phone
► Data Structure
▪ SIM card
► Functionality
▪ Read/write circuitry
Separation of Interface &
Implementation
► Because
interface does not change with the
implementation
Example – Separation of
Interface & Implementation
► Low Complexity
Member Functions
…
void setName(char *newName);
void setRollNo(int newRollNo);
…
};
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;
TypeName VaraibaleName;
int var;
Student aStudent;
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 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
}
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
Object Oriented Programming
(OOP)
Lecture No. 9
Review
Student::Student(
const Student &obj){
rollNo = obj.rollNo;
name = obj.name;
GPA = obj.GPA;
}
Shallow Copy
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
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*/
}
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
studentA M
A
RollNn D
Name
Heap
GPA
Copy Constructor (contd.)
►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
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;
}
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
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;
}
}
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);
…
};
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,…)
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(), …
s1 s2 s3 s4
rollNo, … rollNo, … rollNo, … rollNo, …
address address address address
is internally represented as
void Student::setName(char *,
const Student *)
Declaration of this
DataType * const this;
Compiler Generated Code
Student::Student(){
rollNo = 0;
}
Student::Student(){
this->rollNo = 0;
}
Object Oriented Programming
(OOP)
Lecture No. 11
Review
► this
Pointer
► Separation of interface and implementation
► Constant member functions
Problem
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
s1(rollNo,…)
Static Data Member (Syntax)
class ClassName{
…
static DataType VariableName;
};
Defining Static Data Member
DataType ClassName::VariableName;
Initializing Static Data Member
is equivalent to
int Student::noOfStudents=0;
Object Oriented Programming
(OOP)
Lecture No. 10
Review
►Copy constructors
►Destructor
►Accessor Functions
►this Pointer
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;
}
Example
int main()
{
Student aStudent;
Student bStudent;
bStudent = aStudent.setName(“Ahmad”);
…
bStudent = aStudent.setName(“Ali”).setRollNo(2);
return 0;
}
Separation of interface and
implementation
►Public member function exposed by a
class is called interface
►Separation of implementation from
the interface is good software
engineering
Complex Number
►There are two representations of
complex number
▪ Euler form
►z =x+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
int main(){
Student aStudent;
}
const Member Functions
Definition:
ReturnVal ClassName::Function() const{
…
}
Example
class Student{
public:
int getRollNo() const{
return rollNo;
}
};
const Functions
►Constructorsand Destructors
cannot be const
►Constructor and destructor are
used to modify the object to a well
defined state
Example
class Time{
public:
Time() const {} //error…
~Time() const {} //error…
};
const Function
s1(rollNo,…)
Static Data Member (Syntax)
► Keyword
static is used to make a data
member static
class ClassName{
…
static DataType VariableName;
};
Defining Static Data Member
DataType ClassName::VariableName;
Initializing Static Data Member
is equivalent to
int Student::noOfStudents=0;
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;
};
int Student::noOfStudents;
int main(){
Student aStudent;
aStudent.noOfStudents = 1;
Student::noOfStudents = 1;
}
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;
};
int Student::noOfStudents;
int main(){
Student::noOfStudents = 1;
}
Example
class Student{
public:
static int noOfStudents;
};
int Student::noOfStudents;
int main(){
{
Student aStudent;
aStudent.noOfStudents = 1;
}
Student::noOfStudents = 1;
}
Uses
Output:
0
1
2
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”
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;
int rollNo;
public:
static int getTotalStudent(){
return noOfStudents;
}
};
int main(){
int i = Student::getTotalStudents();
}
Accessing non static data members
int Student::getTotalStudents(){
return 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
Global Variable vs. Static Members
~Date(); //Destructor
};
Implementation of Date Class
Date::~Date
{
}
Getter and Setter
void Date::setMonth(int a){
if(a > 0 && a <= 12){
month = a;
}
int getMonth() const{
return month;
}
addYear
void Date::addYear(int x){
year += x;
if(day == 29 && month == 2
&& !leapyear(year)){
day = 1;
month = 3;
}
}
Helper Function
class Date{
…
private:
bool leapYear(int x) const;
…
};
Helper Function
bool Date::leapYear(int x) const{
if((x%4 == 0 && x%100 != 0)
|| (x%400==0)){
return true;
}
return false;
}
setDefaultDate
void Date::setDefaultDate(
int d, int m, int y){
if(d >= 0 && d <= 31){
day = d;
}
…
}
Recap