Object-Oriented Programming
(OOP)
Course Contents
• Object-Orientation
• Objects and Classes
• Overloading
• Inheritance
• Polymorphism
• Generic Programming
• Exception Handling
• Introduction to Design Patterns
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
• Purpose is to understand the product before
developing it
Examples – Model
• Highway maps
• Architectural models
• Mechanical models
Example – OO Model
…Example – OO Model
lives-in
Ali House
• Objects
– 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
Encapsulation
• Data and behaviour are tightly coupled
inside an object
• Both the information structure and
implementation details of its operations are
hidden from the outer world
Example – Encapsulation
• Ali stores 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
Abstraction
• Abstraction is a way to cope with
complexity.
• Principle of abstraction:
“Capture only those details about an object
that are relevant to current perspective”
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
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
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
Example – Abstraction
A cat can be viewed with different
perspectives
• Ordinary Perspective • Surgeon’s Perspective
A pet animal with A being with
– Four Legs – A Skeleton
– A Tail – Heart
– Two Ears – Kidney
– Sharp Teeth – Stomach
Example – Abstraction
Engineer’s View
Driver’s View
Abstraction – Advantages
• Simplifies the model by hiding irrelevant
details
• Abstraction provides the freedom to defer
implementation decisions by avoiding
commitment to details
Object Oriented Programming
• Programmer thinks about and defines the
attributes and behavior of objects.
• Often the objects are modeled after real-
world entities.
• Very different approach than function-based
programming (like C).
Class: Object Types
• A C++ class is an object type.
• When you create the definition of a class
you are defining the attributes and behavior
of a new type.
• Attributes are data members.
• Behavior is defined by methods.
Creating an object
• Defining a class does not result in creation
of an object.
• Declaring a variable of a class type creates
an object. You can have many variables of
the same type (class).
Instantiation
Information Hiding
• The interface to a class is the list of public
data members and methods.
• The interface defines the behavior of the
class to the outside world (to other classes
and functions that may access variables of
your class type).
• The implementation of your class doesn't
matter outside the class – only the interface.
Information Hiding (cont.)
• You can change the implementation and
nobody cares! (as long as the interface is the
same).
• You can use other peoples classes without
fear!
• Wars will end, poverty and illness will be
vanquished from earth!
Classes
• In an OO model, some of the objects exhibit
identical characteristics (information
structure and behaviour)
• We say that they belong to the same class
Graphical Representation of Classes
(Class Name)
(Class Name)
(attributes)
Suppressed
(operations)
Form
Normal Form
Example – Graphical Representation
of Classes
Circle
center Circle
radius
draw Suppressed
computeArea Form
Normal Form
Example – Graphical Representation
of Classes
Person
name Person
age
gender Suppressed
eat Form
walk
Normal Form
Structures in C / C++
• Structure in C :
– Supports only data abstraction
– Only function pointer can be data member
• Structure in C++
– Supports data abstraction and procedure
abstraction
– Therefore functions can also be members of
structure
Structures in C / C++
Structure in ‘C’ Structure in ‘C++’
struct directory struct directory
{ {
char Name[30]; char Name[30];
long PhoneNo; long PhoneNo;
void Display(void)
{
cout<<PhoneNo;
}
}; };
Class
• struct keyword can be replaced by class keyword
• Generally ‘struct’ is used in ‘C’ context while
‘class’ is used in C++ context
• C++ supports ‘struct’ keyword for compatibility
• Class and object is C++ terminology
Class
• A class is a template for the creation of like objects
• An object is an instance of a class
• Map real world entities into classes through data
members & member functions.
• By writing class & creating objects of that class one
can map two major pillars of object model ie
abstraction & encapsulation into software domain.
• All members of a class data / methods are private by
default.
The challenge of applying Whitner’s method to software
constructs.
Class Syntax
class class name
{
private :
variable declaration ;
function declaration ;
public :
variable declaration ;
function declaration ;
};
If semicolon is missing compiler throws an error
Class Complex : declare class Complex
class Complex class is a keyword
{
private: access specifier
int m_real; data member
int m_imag; data member
public: access specifier
void Display (void); member function
….
}; note semicolon
Object instance of a class
void main (void) //client code
{
Complex c1; // c1 is an object of class Complex
}
Steps in creation of object
Memory is allocated
Constructor is called
Memory gets initialized
Class Complex : default constructor
class Complex
{
……
public:
Complex( ) default constructor
{ written as a inline function
m_real = 0 ;
m_imag = 0 ;
}
};
Class : Constructor
Constructor is a special function with same name as
it’s class name
No need to specify return type for constructor. Not
even void
Constructors are implicitly called when objects are
created
A constructor without input parameter is default
constructor
Constructor can be overloaded
Class Complex : parameterized constructor
class Complex void main (void)
{ {
…… Complex c2(10,20);
public: }
Complex(int r , int i )
{
m_real = r ;
m_imag = i ;
}
};
Class Complex : Few member functions
Class Complex
{
…
public:
void Display (void); //member function declaration
int GetReal(void); //accessor member function
void SetReal(int); // mutator member function
}
Class Complex : Few member functions
void Complex :: Display (void) void main (void)
{ {
char ch; :
ch = (m_imag < 0) ? ’-’ : ‘+’ ; c1.Display( );
cout<< m_real << ch c2.Display( );
<< abs( m_imag ) << “ i “ ; }
}
‘this’ pointer
• Every class member function has hidden
parameter : the this pointer.
• this is a keyword in C++
• this points to an individual object.
• this pointer always holds address of an object
which is invoking the member function.
Class Complex : Few member functions
int Complex :: GetReal (void) void main (void)
{ {
Complex c1,c2(2,4);
return(m_real); int x = c1.GetReal( );
} int y = c2.GetReal( );
or }
int Complex :: GetReal(void)
{
return(this -> m_real);
}
Class Complex
Memory Allocation to objects
C1 C2 C3
m-real m-real m-real
m-imag m-imag m-imag
Member
functions
Class Complex
Create object on heap
void main(void)
{
Complex *p = new Complex (5,7);
……..
delete p ;
}
P Complex
Object
stack heap
Class Complex : const objects
To create constant object use const keyword
const Complex C1(2,3); // statement in main
const objects invoke const member function only
Characteristic of const functions is it is ‘Read Only’ fn.
Class Complex : const objects
int complex :: GetReal() const void main(void)
{ {
return (this -> real); const complex c5(5,7);
} int x = c5.GetReal();
}
Conventional way of writing C++ Program
File : Complex.h File : Complex.cpp
#ifndef COMPLEX_h #include” Complex.h”
#define COMPLEX_h void Complex :: Display()
# include<iostream.h> {
Class Complex …
{ } Server Code
… {
}; …
#endif }
File : TestComplex.cpp Compiler
#include “Complex.h”
int main(void) Complex.obj
{
Client Code Complex c1; TestComplex.obj
…
return 0; Compiler
}
Declaration of Class String
class String
{
private: access specifier
int m_len; data member
char* m_pbuff; pointer as data member
public: access specifier
void Display (void); member function
….
};
Class String : Default Constructor
class String void main(void)
{ {
…… String S1;
public: }
String( ) default constructor
{ written as a inline function
m_len = 0 ; constructors can also be
m_pbuff = new char; written in .cpp file using
*m_pbuff = ‘\0’; scope resolution operator
}
};
Class String : Constructor Overloading
class String void main (void)
{ {
…… String s2(‘S’,10);
public: }
String (char ch , int len )
{
m_len = len ;
m_pbuff = new char [m_len + 1]; // +1 for ‘\0’ char
// for loop or
memset(m_pbuff,ch,m_len); //include memory.h
m_pbuff[m_len] = ‘\0’; //append ‘\0’
}
};
Class String : Constructor Overloading
class String void main (void)
{ {
…… String s3(“SEED”);
public: }
String (const char *p )
{
m_len = strlen(p);
m_pbuff = new char [m_len + 1]; // +1 for ‘\0’ char
strcpy ( m_pbuff,p) //include string.h
}
};
Class : Destructor
• Destructor is also a special function with the
same name as class name prefixed by ~
character.Eg ~Complex( ) ; or ~String( );
• No need to specify return type or parameters to
destructor function.
• Destructor cannot be overloaded. Therefore a class
can have only one destructor.
• Destructor is implicitly called whenever an object
ceases to exist.
Class : Destructor
• Destructor function de-initializes the
objects when they are destroyed.
• A destructor is automatically invoked when
object goes out of scope or
when the memory allocated to object is de-
allocated using the delete operator.
• If a class contains pointer variable then it is
mandatory on programmers part to write a
destructor otherwise there is problem of
memory leakage.
Class : Destructor
Class String
{
…...
public:
~String( )
{
if(m_pbuff)
delete [ ] m_pbuff;
}
};
Object Creation/Destruction
• Sequence for object creation
1) Memory is allocated
2) Constructor is called
3) Memory is initialized
• Sequence for object destruction
1) Destructor is called
2) If memory is allocated dynamically it is freed
3) Memory allocated to object is de-allocated only
when object goes out of scope.
Scope of an Object
Class Test
{……
public:
Test( )
{ cout<<“Constructor is invoked”<<endl; }
~Test( )
{ cout << “Destructor is invoked<<endl; “ }
};
Scope of an Object
Test t1;
void main (void)
{ cout<<“main begins”;
Test t2;
{
cout<<“Block begins”<<endl;
Test t3;
cout<<“Block Ends”<<endl;
}
cout<<“main ends”<<endl;
}
Class String : Copy Constructor
String s4(s3); // To create s4 as a copy of s3
The implicit Copy Constructor does a member wise
copy of the elements:
s3 s4
Gets copied
4 4
Gets copied
1001 1001
1001
S E E D \0
If one object goes out of scope this situation leads to the
problem of dangling pointer.
Class String : Copy Constructor
To avoid problem of dangling pointer it is mandatory to
have a copy constructor in a class which contains a
pointer variable
s3 s4
Gets copied
4 4
1001 3003
1001 3003
S E E D \0 S E E D \0
Copy constructor creates a new space in the heap for the
string to be copied.
Class String : Copy Constructor
class String void main (void)
{ {
…… String s4(s3);
public: }
String (const String &s ) //pass by reference
{
m_len = s.m_len;
m_pbuff = new char [m_len + 1];
strcpy ( m_pbuff,s.m_pbuff)
}
};
Class String : Copy Constructor
• While creating copy of an object you should
know
– Compiler provides a default copy constructor which
does member wise copy.
– If a class contains one of it’s data member as a pointer
type variable, it’s mandatory on programmer’s part to
write user defined copy constructor.
– User defined copy constructor should take care of
dangling pointer situation.
– To avoid infinite recursion, pass the parameters by
reference to the copy constructor.
Static Data Members
Data to be shared by all objects is stored in static data
members.
It’s a class variable
Only single copy exists
Scope and lifetime of static variable
Static Member Functions
Static member functions can access static data
members only.
Static member function is invoked using class name
class name : : function name()
Pointer this is never passed to a static member
function
Static Objects in Memory
C1 C2 C3
m-real m-real m-real
m-imag m-imag m-imag
count
Static members
•Only one copy of the variable exists(even when inherited)
•It is a way of defining a global variable bound to a class
•Can be accessed with or without object reference.
•The members are initialized to default values
•Static functions can access only static members
•Are used for initialization of static members
Static members
class myclass void main()
{ {
static int var; myclass::var=200;
public: myclass::var1=100;
void display() myclass obj1,obj2;
{ cout<<obj1.var1<<obj2.var;
cout<<var;
} }
void accept()
{
cin>>myclass::var;
}
};
int myclass ::var;
int myclass::var1;
STATIC FUNCTIONS
•USED TO SET VALUES OF STATIC MEMBERS ONLY
•CANNOT ACCESS NON-STATIC MEMBERS BECAUSE
THEY REQUIRE OBJECT REFERENCE
•CAN BE CALLED DIRECTLY WITHOUT OBJECT
REFERENCE
•THERE IS ONLY ONE COPY OF THE FUNCTION
STATIC member function:
static return_type fun_name( )
{
----------------
}
calling static member function:
class name :: fun_name( ) ;
Static Members(Exercise)
•class myclass
{
int var;
static int statvar;
public:
static void setfunc()
{
statvar=100;
var=20;
}
void set()
{
statvar=200;
var=30;
}
};
Constant and mutable specifiers
Constant members
class myclass void main()
{ {
int x; myclass obj1,obj3;
public: const myclass obj2=obj1;
void func(int m) obj2=obj3;
{ obj2.func();
x=m;
} }
};
Constant specifiers
class myclass
{
int x;
int y;
public:
void func(int m)const
{
x=m;
}
};
void main()
{
myclass obj;
obj.func(10);
}
Constant specifier
class myclass
{
int x;
mutable int y;
public:
void func(int m)const
{
y=m;
}
};
void main()
{
myclass obj;
obj.func(10);
}
Constant specifiers
•Constant functions cannot change the data members
•Constant functions can be invoked by both constant and
non constant objects
•To allow some of the variables to be changed mutable
specifier is used
•Constant objects cannot invoke non-constant member
functions
Friends of Classes
• A friend function of a class is a function that is not a
member of a class, but has access to the private members of
the class.
• A friend function is declared with the keyword friend.
friend <return type><function name>(<parameter type list>);
• Using friend functions is a way of breaking the rule of
encapsulation. As such, friend functions should only be used
when absolutely necessary.
• A Friend function can be friend of many classes
• A fiend function has no object reference and do not have the
this pointer
Friend functions(examples)
class myclass
{
public:
friend void func();
};
void func()
{….}
void main()
{
func();
}
Friend functions(exercise)
class myclass
{
int x;
public:
myclass(){
x=10;
}
friend void myfunc();
};
void myfunc()
{
cout<<x;
}
void main()
{
func();
}
Friend functions
class myclass void myfunc()
{ {
int x; …..
public: }
myclass(){
x=10;
}
friend void myfunc();
};
class myclass1
{
friend void func();
};
Friend functions
class myclass
void func()
{ {
int x; myclass obj;
myclass(){ obj.display();
x=10;
}
}
public:
void display()
{
cout<<x;
}
friend void myfunc();
};
Friend functions
class myclass
{
int x;
public: void main()
myclass(){ {
x=10; func();
} myclass obj;
private: obj.func();
friend void myfunc(); }
};
void func()
{
….
}
Friend functions
class myclass
{
int x;
public:
myclass(){
x=10;
}
void myfunc(){ ……..}
};
class myclass1
{
friend void myclass::func();
};
Friend classes
• As mentioned before, it is possible to make an entire
class a friend of another class.
• When a class is declared as a friend of another class
every member function of the friend class is a friend
function to the other class.
Friend classes
class myclass1 class myclass2
{ {
private: private:
int var1; int var2;
public: public:
void func1() void func2()
{ {
myclass2 ob; myclass1 obj;
cout<<ob.var2; cout<<obj.var1;
} }
friend class myclass2; friend class myclass1;
}; };
Friend classes
class myclass1 class myclass2
{ {
private: private:
int var1; int var2;
public: public:
friend class myclass2; void func2()
}; {
cout<<var1;
}
friend class myclass1;
};