Object Oriented Programming
Lecture 3
Dr. Jawad Manzoor
Original slides by: Dr. Naveed Anwar Bhatti
Object Oriented Modeling
Concepts
Last Class
• Model
• Object Oriented Model
• Object
Stores Change internal state
• State Fields
• Behavior
Implementation
• Identity
Interfaces
Exposes their
functionality through
3
Abstraction
• Abstraction is a way to cope with complexity.
• Principle of abstraction:
“ Capture only those details about an object that are relevant to
current perspective ”
4
Abstraction - Example
unclassified “organisms" organisms, mammals, humans organisms, mammals,
dangerous mammals
5
Abstraction - Example
The selection of significant attributes (to allow us to classify the
items that possess them) is abstraction
unclassified "things" organisms, mammals, humans organisms, mammals,
dangerous mammals
6
Abstraction – Advantages
• The selection of significant attributes (to allow us to classify the items
that possess them) is abstraction.
• We can abstract by appearance, structure, purpose, functionality,
privilege etc.
• In OOP we specify classes that will form the elements of our
programs. When the program is executed it makes software objects
that are instances of these classes and allows them to interact with
one another (by passing messages) to solve the problems that we set.
7
Class
• In an OO model, some of the objects exhibit
identical characteristics (information
structure and behavior)
Organisms
Mammals
• We say that they belong to the same class
Humans 8
Class
• What is Class?
o Class is a blueprint from which individual objects are created
o An expanded concept of data structures: like data structures, they can
contain data members, but they can also contain functions as members.
Classname Rectangle Circle
width radius
Class
Data Memebers
height color
Member Functions setValues() getRadius()
area() area()
Few More Examples – Class
• Ali studies mathematics
• Anam studies physics
• Sohail studies chemistry
• Each one is a Student
• We say these objects are instances of the Student class
10
Few More Examples – Class
• Ahsan teaches mathematics
• Aamir teaches computer science
• Atif teaches physics
• Each one is a Teacher
• We say these objects are instances of the Teacher class
11
Graphical Representation of Classes
(Class Name)
(Class Name)
(states)
Suppressed
(behavior) Form
Normal Form
Example - Graphical Representation of Classes
Circle
• center Circle
• radius Suppressed
Suppressed
draw() Form
Form
computeArea()
Normal
NormalForm
Form
13
Example - Graphical Representation of Classes
Person
• Name
• Age Person
• Gender
Suppressed
eat() Form
walk()
Normal Form
14
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
• Member functions are the functions that operate on the data
encapsulated in the class
• Public member functions are the interface to the class
o Class members (both data and functions)can restrict their access
through access specifiers
Classes Intro: Access Specifier
• An access specifier determines what kind of access do you
want to give to class members
• Access can be of three types:
• Private: members of a class are accessible only from within the same
class
• Protected: members of a class are not accessible from outside, but is
accessible from the members of any class derived from same class
• Public: members are accessible from anywhere where the object is
visible
Class definition
• A class definition starts with the keyword class followed by the
class name
Class definition
• Complete example:
Accessor
Functions
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
Class: Scope Operator
• Outside Class:
Scope Operator
Class: Scope Operator
• Another Example:
#include <iostream>
using namespace std;
class Student
{
int rollNo;
public:
void setRollNo(int aRollNo);
}; Scope Operator
void Student::setRollNo(int aRollNo)
{
rollNo = aRollNo;
}
Inline Functions
Inline Functions
• Instead of calling an inline function compiler places a copy of the
code at the function call point
• Keyword ‘inline’ is used to request compiler to make a function inline
Example
#include <iostream> #include <iostream>
using namespace std; using namespace std;
inline void hello()
{ int main()
cout << "Hello World"; {
} cout << "Hello World";
}
int main()
{
hello();
}
Inline Functions
• It is a request and not a command. Compiler may not perform inlining
in such circumstances like:
1. If a function contains a loop. (for, while, do-while)
2. If a function contains static variables.
3. If a function is recursive.
4. If a function contains switch or goto statement.
Inline Functions – Advantages and Disadvantages
Advantages:
1. Function call overhead doesn’t occur.
2. It also saves the overhead of push/pop variables on the stack when function
is called.
3. It also saves overhead of a return call from a function.
Disadvantages:
1. Too many inline functions will increase the size of the binary executable because
of the duplication of same code.
2. Inline function may increase compile time overhead. If someone changes the
code inside the inline function then all the calling location has to be recompiled.
3. Inline functions may not be useful for many embedded systems. Because in
embedded systems code size is more important than speed.
Inline Functions and Classes
• 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
Inline Functions and Classes: Example
#include <iostream>
using namespace std;
class Student
{
int rollNo;
public:
inline void setRollNo(int aRollNo);
};
inline void Student::setRollNo(int aRollNo)
{
rollNo = aRollNo;
}
Constructor & Destructor
What would happen if we called member function area() before
having called set_values(int, int)?
Class: Constructor
• Class can include a special function called its constructor
• Constructor is used to ensure that object is in well defined state at the time
of creation
• Automatically called when new object is created, allowing class to initialize
member variables or (allocate storage). Cannot be called explicitly using
existing object
• Declared just like regular member function, but with a name that matches
the class name and without any return type; not even void
Class: Constructor
Output:
Types of Constructor
• Default constructor
• Parameterized constructor
• Copy constructor
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
• Compiler created default constructor has empty body, i.e., it doesn’t
assign default values to data members
• User created default constructor can assign default values to data
members
Constructors Overloading
o Like function, constructor can also be overloaded with different versions
taking different parameters
Constructors Overloading
• Complete Example
default constructor
Constructors Overloading
Note:
Whenever we define one or more non-default constructors( with
parameters ) for a class, a default constructor( without parameters
) should also be explicitly defined as the compiler will not provide a
default constructor in this case
Constructors Overloading
• Use default parameter value to reduce the writing effort
Rectangle::Rectangle(int a=0, int b=0)
{
width = a;
height = b;
}
• Is equivalent to
Rectangle::Rectangle()
Rectangle::Rectangle(int a)
Rectangle::Rectangle(int a, int b)
Class: Destructor
• Automatically called when class object passes out of scope or is explicitly
deleted
• Mainly used to de-allocate the memory that has been allocated for the
object by the constructor (or any other member function).
• Syntax is same as constructor except preceded by the tilde sign
• Neither takes any arguments nor does it returns value
• Can’t be overloaded
Class: Destructor
• If we do not write our own destructor in class, compiler creates a default
destructor for us.
• The default destructor works fine unless we have dynamically allocated
memory or pointer in class.
• When a class contains a pointer to memory allocated in class, we should
write a destructor to release memory before the class instance is
destroyed. This must be done to avoid memory leak.
Class: Destructor
• Example
Dynamic memory
• In the programs seen in previous chapters, all memory needs were
determined before program execution by defining the variables
needed.
• But there may be cases where the memory needs of a program can
only be determined during runtime.
• For example, when the memory needed depends on user input.
• On these cases, programs need to dynamically allocate memory,
for which the C++ language integrates the
operators new and delete.
Dynamic memory
•There are two ways that memory gets allocated for data storage
•Compile Time (or static) Allocation
• Memory for named variables is allocated by the compiler
• Exact size and type of storage must be known at compile time
• For standard array declarations, this is why the size has to be constant
•Dynamic Memory Allocation
• Memory allocated "on the fly" during run time
• Exact amount of space or number of items does not have to be known
by the compiler in advance.
• For dynamic memory allocation, pointers are crucial
Dynamic memory
•We can dynamically allocate storage space while the program is
running, but we cannot create new variable names "on the fly"
•For this reason, dynamic allocation requires two steps:
• Creating the dynamic space.
• Storing its address in a pointer (so that the space can be accessed)
•To dynamically allocate memory in C++, we use
the new operator.
Dynamic memory
• Examples
int * p = new int; // dynamic integer, pointed to by p
*p = 10; // assigns 10 to the dynamic integer
cout << *p; // prints 10
double * numList = new double[size]; // dynamic array
for (int i = 0; i < size; i++)
numList[i] = 0; // initialize array elements to 0
Dynamic memory
Problem:
Cant create a shape object with different
number of sides at runtime.
Dynamic memory
Output:
Dynamic memory
Output:
Sequence of Calls
•[Again Remember] Constructors and destructors are called
automatically
•Constructors are called in the sequence in which object is
declared
•Destructors are called in reverse order
Sequence of Calls
#include <iostream>
using namespace std;
int main()
{
class Sequence {
int check; Sequence rect1(1);
public: Sequence rect2(2);
Sequence(int a);
~Sequence(); return 0;
}; }
Sequence::Sequence(int a)
{
check = a;
cout << "I am in constructor " << check << endl;
}
Sequence::~Sequence()
{
cout << "I am in destructor " << check << endl;
}