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

Lecture01, Lecture02, Defining Class and Objects

Uploaded by

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

Lecture01, Lecture02, Defining Class and Objects

Uploaded by

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

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

► Assignments 15 %
► Group Discussion 5%
► Mid-Term 35 %
► Final 45 %
Object-Orientation (OO)
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
Examples – Model

► 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

► OO models map to reality

► Therefore, OO models are


▪ easy to develop
▪ easy to understand
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
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

► Information is stored within the object

► It is hidden from the outside world

► It can only be manipulated by the object


itself
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

► Wecan’t read the numbers directly from the


SIM card

► Rather phone-set reads this information for


us
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

► Boththe information structure and


implementation details of its operations are
hidden from the outer world
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
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
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
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
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
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


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
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
Object oriented programming
(OOP)
Lecture No. 7
Class
► Class is a tool to realize objects
► Class is a tool for defining a new type
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
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
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;
char *address;

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;

aStudent.rollNo = -514; //Error


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;
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;
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
Example
class Student{
private:
char * name;
Cannot be accessed outside class
int rollNo;
public:
void setName(char *); Can be
accessed
void setRollNo(int);
outside class
...
};
Example
class Student{
...
int rollNo;
public:
void setRollNo(int aNo);
};
int main(){
Student aStudent;
aStudent.SetRollNo(1);
}
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;
};
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”);
Object Oriented Programming
(OOP)
Lecture No. 8
Review
► Class
▪ Concept
▪ Definition
► Data members
► Member Functions
► Access specifier
Member Functions
► Member functions are the functions that
operate on the data encapsulated in the
class
► Public member functions are the interface to
the class
Member Functions (contd.)
► Define member function inside the class
definition
OR
► Define member function outside the class
definition
▪ But they must be declared inside class definition
Function Inside Class Body
class ClassName {

public:
ReturnType FunctionName() {

}
};
Example
►Define a class of student that
has a roll number. This class
should have a function that
can be used to set the roll
number
Example
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){
rollNo = aRollNo;
}
};
Function Outside Class Body
class ClassName{

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

Scope
} resolution
operator
Example
class Student{

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

rollNo = aRollNo;
}
Inline Functions
► Instead of calling an inline function compiler
replaces the code at the function call point
► Keyword ‘inline’ is used to request compiler
to make a function inline
► It is a request and not a command
Example
inline int Area(int len, int hi)
{
return len * hi;
}
int main()
{
cout << Area(10,20);
}
Inline Functions
► If we define the function inside the class
body then the function is by default an
inline function
► In case function is defined outside the class
body then we must use the keyword ‘inline’
to make a function inline
Example
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){

rollNo = aRollNo;
}
};
Example
class Student{

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

rollNo = aRollNo;
}
Example
class Student{

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

rollNo = aRollNo;
}
Example
class Student{

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

rollNo = aRollNo;
}
Constructor
Constructor
► Constructor is used to initialize the objects
of a class
► Constructor is used to ensure that object is
in well defined state at the time of creation
► Constructor is automatically called when the
object is created
► Constructor are not usually called explicitly
Constructor (contd.)
► Constructor is a special function having
same name as the class name
► Constructor does not have return type
► Constructors are commonly public members
Example
class Student{

public:
Student(){
rollNo = 0;

}
};
Example
int main()
{
Student aStudent;
/*constructor is implicitly
called at this point*/
}
Default Constructor
► Constructor without any argument is called
default constructor
► If we do not define a default constructor the
compiler will generate a default constructor
► This compiler generated default constructor
initialize the data members to their default
values
Example
class Student
{
int rollNo;
char *name;
float GPA;
public:
… //no constructors
};
Example
Compiler generated default constructor
{
rollNo = 0;
GPA = 0.0;
name = NULL;
}
Constructor Overloading
► Constructors
can have parameters
► These parameters are used to initialize the
data members with user supplied data
Example
class Student{

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

}
Example
int main()
{
Student student1;
Student student2(“Name”);
Student student3(”Name”, 1);
Student student4(”Name”,1,4.0);
}
Constructor Overloading
► Use default parameter value to reduce the
writing effort
Example
Student::Student( char * aName = NULL,
int aRollNo= 0,
float aGPA = 0.0){

}
Is equivalent to
Student();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(char * Name, int aRollNo, float
aGPA);
Copy Constructor
► Copy constructor are used when:
▪ Initializing an object at the time of creation
▪ When an object is passed by value to a function
Example
void func1(Student student){

}
int main(){
Student studentA;
Student studentB = studentA;
func1(studentA);
}
Copy Constructor (Syntax)
Student::Student(
const Student &obj){
rollNo = obj.rollNo;
name = obj.name;
GPA = obj.GPA;
}
Shallow Copy
► When we initialize one object with another
then the compiler copies state of one object
to the other
► This kind of copying is called shallow
copying
Example

Student studentA;
Student studentB = studentA;

studentA 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

►Member functions implementation


►Constructors
►Constructors overloading
►Copy constructors
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);
}
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
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
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.)

►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
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;
}
}
}
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
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(), …

•How does the functions know on which


object to act?
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
Example
void Student::setName(char *)

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

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

};
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*/
}
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
Example
class Student{
const int rollNo;
char *name;
float GPA;
public:
Student(int 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
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 */
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;
}
Example
class Student{

int rollNo;
public:

int getRollNo(){
return rollNo;
}
};
Example
int main(){
const Student aStudent;
int a = aStudent.getRollNo();
//error
}
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;
}
};
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
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
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
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;
};
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;
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*/
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;
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

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)
… …
Example
class Complex{ //old
float x;
float y;
public:
void setNumber(float i, float j){
x = i;
y = j;
}

};
Example
class Complex{ //new
float z;
float theta;
public:
void setNumber(float i, float j){
theta = arctan(j/i);

}

};
Advantages

►User is only concerned about ways


of accessing data (interface)
►User has no concern about the
internal representation and
implementation of the class
Separation of interface and
implementation
►Usually functions are defined in
implementation files (.cpp) while
the class definition is given in
header file (.h)
►Some authors also consider this as
separation of interface and
implementation
Student.h
class Student{
int rollNo;
public:
void setRollNo(int aRollNo);
int getRollNo();

};
Student.cpp
#include “student.h”

void Student::setRollNo(int aNo){



}
int Student::getRollNo(){

}
Driver.cpp
#include “student.h”

int main(){
Student aStudent;
}
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
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{

}
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
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;
}
Example
bool Student::isRollNo
(int aNo)const{
/*compiler error*/
if(rollNo = aNo){
return true;
}
return false;
}
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

►Constant member function


cannot change data member
►Constant member function
cannot access non-constant
member functions
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;
Object Oriented Programming
(OOP)
Lecture No. 12
Review
► Constant data members
► Constant objects
► Static data members
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
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;
};
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;
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*/
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;
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

►They can be used to store


information that is required by
all objects, like global variables
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;
Student();
~Student();

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

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

►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
Example
class Test{
public:
};
int main(){
Test array[2]; // OK
}
Example
class Test{
public:
Test();
};
int main(){
Test array[2]; // OK
}
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)};
}
Example
class Test{
public:
Test(int i);
}
int main(){
Test a(1),b(2);
Test array[2] = {a,b};
}
Object Oriented Programming
(OOP)
Lecture No. 13
Review
► Static data members
► Static member functions
► Array of objects
Pointer to Objects
► Pointer to objects are similar as pointer to
built-in types
► They can also be used to dynamically
allocate objects
Example
class Student{

public:
Studen();
Student(char * aName);
void setRollNo(int aNo);
};
Example
int main(){
Student obj;
Student *ptr;
ptr = &obj;
ptr->setRollNo(10);
return 0;
}
Allocation with new Operator

► new operator can be used to create objects


at runtime
Example
int main(){
Student *ptr;
ptr = new Student;
ptr->setRollNo(10);
return 0;
}
Example
int main(){
Student *ptr;
ptr = new Student(“Ali”);
ptr->setRollNo(10);
return 0;
}
Example
int main()
{
Student *ptr = new Student[100];
for(int i = 0; i < 100;i++)
{
ptr->setRollNo(10);
}
return 0;
}
Breakup of new Operation

► new operator is decomposed as follows


▪ Allocating space in memory
▪ Calling the appropriate constructor
Case Study
Design a class date through which user must be able
to perform following operations
▪ Get and set current day, month and year
▪ Increment by x number of days, months and year
▪ Set default date
Attributes
► Attributes
that can be seen in this problem
statement are
▪ Day
▪ Month
▪ Year
▪ Default date
Attributes
► 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;

};
Interfaces
► getDay ► addDay
► getMonth ► addMonth
► getYear ► addYear
► setDay ► setDefaultDate
► setMonth
► setYear
Interfaces
► Asthe default date is a static member the
interface setDefaultDate should also be
declared static
Interfaces in Date.h
class Date{

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


};
Interfaces in Date.h
class Date{

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

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

~Date(); //Destructor
};
Implementation of Date Class

► The static member variables must be


initialized

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


Constructors
Date::Date(int aDay, int aMonth,
int aYear) {
if(aDay==0) {
this->day = defaultDate.day;
}
else{
setDay(aDay);
}
//similarly for other members
}
Destructor
► Weare not required to do any house
keeping chores in destructor

Date::~Date
{
}
Getter and Setter
void Date::setMonth(int a){
if(a > 0 && a <= 12){
month = a;
}
int getMonth() const{
return month;
}
addYear
void Date::addYear(int x){
year += x;
if(day == 29 && month == 2
&& !leapyear(year)){
day = 1;
month = 3;
}
}
Helper Function
class Date{

private:
bool leapYear(int x) const;

};
Helper Function
bool Date::leapYear(int x) const{
if((x%4 == 0 && x%100 != 0)
|| (x%400==0)){
return true;
}
return false;
}
setDefaultDate
void Date::setDefaultDate(
int d, int m, int y){
if(d >= 0 && d <= 31){
day = d;
}

}
Recap

You might also like