Object Oriented Programming
BSE II
Lecture 03
Instructor: Bushra Bashir Chaoudhry
What are objects?
An object represents an individual,
identifiable item, unit, or entity, either real or
abstract, with a well-defined role in the
problem domain.
Or
An "object" is anything to which a concept
applies.
Why do we care about objects?
Modularity - large software projects can be
split up in smaller pieces.
Reusability - Programs can be assembled from
pre-written software components.
Extensibility - New software components can
be written or developed from existing ones.
The two parts of an object
Object = Data + Methods
or to say the same differently:
An object has the responsibility to know and
the responsibility to do.
= +
Basic Terminology
Abstraction is the representation of the essential
features of an object. These are ‘encapsulated’ into an
abstract data type.
Encapsulation. There should be tight coupling
between data and methods that operate on this data.
Such data should be hidden from the code outside the
current context. This process of data hiding and
combining data and methods in a single logical unit is
called encapsulation. The internal state is usually not
accessible by other objects.
Basic Terminology:
Inheritance
Inheritance means that one class inherits the
characteristics of another class.
This is also called a “is a” relationship:
A car is a vehicle
A dog is an animal
A teacher is a person
Polymorphism
Functionality name remains the same, while
the implementation varies across different
parent and child classes.
Poly= many
Morph=faces
Classes
A class is an expanded concept of a data
structure: instead of holding only data, it can
hold both data and functions.
The data and methods that operate on this data
are encapsulated in a single package called
“calss”.
An object is an instantiation of a class. In
terms of variables, a class would be the type,
and an object would be the variable.
Class
Classes are generally declared using the keyword
class, with the following format:
class class_name
{
access_specifier_1:
member1;
access_specifier_2:
member2;
... } object_names;
Class
class_name is a valid identifier for the class.
object_names is an optional list of names for
objects of this class.
The body of the declaration can contain
members, that can be either data or function
declarations, and optionally access specifiers.
Difference of Classes from Structure
All is very similar to the declaration on data
structures except
that we can now include also functions and data
members.
but also this new thing called access specifier
“An access specifier is one of the following three
keywords: private, public or protected. “
Access Specifiers
private members of a class are accessible only from
within other members of the same class or from their
friends.
protected members are accessible from members of
their same class and from their friends, but also from
members of their derived classes.
public members are accessible from anywhere where
the object is visible.
N.B: All members of a class declared with the class
keyword have private access for all its members.
A Simple Class Declaration
class CRectangle
{ int a;
int x, y;
public:
void set_values (int,int);
int area (void);
} rect;
This class contains four members: two data members of type
int (member x and member y) with private access and two
member functions with public access: set_values() and area(),
we have only included their declaration, not their definition.
2-A Class Example
#include <iostream>
using namespace std;
class CRectangle int main ()
{
int x, y;
{
public: CRectangle rect;
void set_values (int a, int b)
{ rect.set_values (3,4);
x = a;
cout << "area: " <<
y = b;
} [Link]();
} int area ()
{
return 0;
return (x*y); }
}
};
2-A Class Example
#include <iostream> void CRectangle::set_values (int a,
int b)
using namespace std; {
class CRectangle x = a;
{ y = b;
int x, y; }
int main ()
public:
{
void set_values (int,int); CRectangle rect,rect1;
int area () rect.set_values (3,4);
{ rect1.set_values (5,6);
return (x*y); cout << "area: " << [Link]();
cout << "area: " << [Link]();
} return 0;
}; }
A Class Example
the definition of the member function area() has been
included directly within the definition of the
CRectangle class.
set_values() has only its prototype declared within the
class, but its definition is outside it.
In outside declaration, we must use the operator of
scope (::) to specify that we are defining a function
that is a member of the class CRectangle and not a
regular global function.
Operator of Scope
The scope operator (::) specifies the class to
which the member being declared belongs,
granting exactly the same scope properties as
if this function definition was directly included
within the class definition.
One of the greater advantages of a class is that,
as any other type, we can declare several
objects of it. e.g.
CRectangle rect,rect1;
A Class Example
rect and rect1 has its own member variables
and member functions.
Call to [Link]() does not give the same
result as the call to [Link]().
each object of class CRectangle has its own
variables x and y.
They also have their own function members
set_value() and area() that each uses its object's
own variables to operate.
Conclusion
That is the basic concept of object-oriented
programming:
Data and functions are both members of the object. We
no longer use sets of global variables that we pass from
one function to another as parameters, but instead we
handle objects that have their own data and functions
embedded as members.
N.B: We have not had to give any parameters in any of
the calls to [Link]() or [Link](). Those member
functions directly used the data members of their
respective objects rect and rect1.
Object Oriented Programming
BSE II
Lecture 04
Instructor: Bushra Bashir Chaoudhry
Overloaded functions.
In C++ two different functions can have the
same name if their parameter types or number
are different.
Such functions are called “Overloaded
Functions”.
Overloaded Functions
#include <iostream> int main ()
using namespace std; {
int operate (int a, int b) int x=5,y=2;
{ float n=5.0,m=2.0;
return (a*b); cout << operate (x,y);
} cout << "\n";
float operate (float a, float b) cout << operate (n,m);
{ cout << "\n";
return (a/b); return 0;
} }
A Class Example
#include <iostream> void CRectangle::set_values (int a, int b)
using namespace std; {
class CRectangle x = a;
y = b;
{
}
int x, y;
int main ()
public: {
void set_values (int,int); CRectangle rect,rect1;
int area () rect.set_values (3,4);
{ rect1.set_values (5,6);
return (x*y); cout << "area: " << [Link]();
} cout << "area: " << [Link]();
}; return 0;
}
Constructors
Objects generally need to initialize variables or assign
dynamic memory during their process of creation to
become operative and to avoid returning unexpected
values during their execution.
What would happen if in the previous example we
called the member function area() before having
called function set_values() ?
Probably we would have gotten an undetermined result
since the members x and y would have never been assigned
a value.
Constructor
In order to avoid that, a class can include a
special function called constructor, which is
automatically called whenever a new object of
this class is created.
This constructor function must have the same name as
the class, and cannot have any return type; not even
void.
“A class method having the same name as the class
name is called the class constructor.”
#include <iostream> Dynamics int main ()
using namespace std; object
{
class CRectangle
{
CRectangle rect (3,4);
int width, height; CRectangle *rectb = new
public: CRectangle(5,6);
CRectangle (int,int);
int area () cout << "rect area: " <<
{ [Link]() << endl;
return (width*height);
}
cout << "rectb area: " <<
}; rectb->area() << endl;
CRectangle::CRectangle (int a, int b)
{
return 0;
width = a; }
height = b;
}
Constructors
we have removed the member function set_values(),
and have included instead a constructor that performs
a similar action.
It initializes the values of width and height with the
parameters that are passed to it.
CRectangle rect (3,4);
Passing the arguments to the constructor is also
different
CRectangle *rectb = new CRectangle(5,6);
N.B: rectb is a dynamic object that is created at
run time.
Dynamic Objects
The memory allocation for the CRectangle object
rectb is done at compile time, at certain times you
will wish to create objects at run time and delete them
as they are no more required by application. This
results in better memory usage.
To create dynamic objects- new is used.
CRectangle *rectb;
rectb = new CRectangle();
To delete dynamically created objects- delete is used.
delete rectb;
Constructors
Constructors cannot be called explicitly as if they
were regular member functions. They are only
executed when a new object of that class is created.
N.B: Neither the constructor prototype declaration
(within the class) nor the latter constructor definition
include a return value; not even void.
Overloading Constructors
/Multiple Constructors
Like any other function, a constructor can also
be overloaded with more than one function
that have the same name but different types or
number of parameters.
include <iostream> CRectangle::CRectangle (int a, int b)
using namespace std; {
class CRectangle width = a;
{ height = b;
int width, height; }
public: int main ()
CRectangle (int,int); {
CRectangle (); CRectangle rect (3,4);
CRectangle rectb;
int area (void)
cout << "rect area: " << [Link]() <<
{ endl;
return (width*height); cout << "rectb area: " << [Link]() <<
} endl;
}; return 0;
CRectangle::CRectangle () }
{
width = 5;
height = 5;
}
Overloading Constructors
rectb was declared without any arguments, so
it has been initialized with the constructor that
has no parameters, which initializes both width
and height with a value of 5.
Object Oriented Programming
BSE II
Lecture 05
Instructor: Bushra Bashir Chaoudhry
Default Constructors
When you create an object, if you do not
declare a constructor, the compiler would
create one for your program; this is useful
because it lets all other objects and functions
of the program know that this object exists.
This compiler created constructor is called the
default constructor.
Default Constructors
#include <iostream> int main()
using namespace std;
class Book {
{ Book B;
public:
Book();
return 0;
}; }
Book::Book()
{
cout << "I see a book...\n";
}
Copy Constructor
At certain times you may wish to create a copy of an
existing object.
A copy constructor is a special constructor in the C+
+ programming language used to create a new object
as a copy of an existing object.
C++ defines two distinct types of situations in which
the value of one object is given to another.
The first is assignment.
The second is initialization.
When is the copy constructor needed?
Copy constructor is needed when you want to initialize one
object with another, this is done in 3 ways:
When one object explicitly initializes another, such as in a
declaration
myclass x = y; // y explicitly initializing x
When a copy of an object is made to be passed to a function
func(y); // y passed as a parameter
When a temporary object is generated (most commonly, as a
return value)
y = func(); // y receiving a temporary, return object
Arguments to a copy constructor?
For initialization create a constructor in your
class definition that takes the object to be
copied as an argument.
N.B: It is permissible for a copy constructor to have
additional parameters as long as they have default arguments
defined for them. However, in all cases the first parameter
must be a reference to the object doing the initializing.
An Example-Copy Constructor
class Point
{ int getX()
private:
int x, y; {
public: return x;
Point(int x1, int y1)
{
}
x = x1; int getY()
y = y1; } {
// Copy constructor return y;
Point(const Point &p2) }
{
x = p2.x;
};
y = p2.y;
}
An Example-Copy Constructor(Cont’d)
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Point p2 ( p1); // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << [Link]() << ", p1.y = " << [Link]();
cout << "\np2.x = " << [Link]() << ", p2.y = " << [Link]();
return 0;
}
Destructors
The destructor fulfills the opposite functionality.
It is automatically called
When an object is destroyed, either because its scope of
existence has finished (for example, if it was defined as a
local object within a function and the function ends)
When an object dynamically assigned and it is released
using the operator delete.
The destructor must have the same name as the class,
but preceded with a tilde sign (~) and it must also
return no value.
#include <iostream> CRectangle::~CRectangle
using namespace std; ()
class CRectangle
{
{
int *width, *height; delete width;
public: delete height;
CRectangle (int,int);
~CRectangle (); }
int area () int main ()
{
return (*width * *height);
{
} CRectangle rect (3,4);
}; CRectangle rectb (5,6);
CRectangle::CRectangle (int a, int b)
{ cout << "rect area: " <<
width = new int; [Link]() << endl;
height = new int; cout << "rectb area: " <<
*width = a; [Link]() << endl;
*height = b;
} return 0;
}
The use of destructors
It is especially suitable when an object assigns
dynamic memory during its lifetime and at the
moment of being destroyed we want to release
the memory that the object was allocated.
Friend Functions
In principle, private and protected members of a class
cannot be accessed from outside the same class in
which they are declared. However, this rule does not
affect friends.
A friend function is used for accessing the non-public
members of a class. A class can allow non-member
functions and other classes to access its own private
data, by making them friends.
A friend function can be an ordinary function or a
member of another class.
Friend Functions
If we want to declare an external function as
friend of a class. We do it by
declaring a prototype of this external function
within the class,
preceding it with the keyword friend.
It is possible to declare a function as friend in any
number of classes.
It is possible to declare the friend function as either
private or public.
The function can be invoked without the use of an
object. The friend function has its argument as objects.
Friends Functions
int backdoorCall(Bank b1)
#include<iostream> {
#include<conio.h> cout<<"backdoor can access
variable of object b1 whose
using namespace std; value is "<<b1.a;
return b1.a;
class Bank
}
{
int a,b; main()
public: {
void test() Bank b1;
{ [Link]();
a=100; cout<<"The result is:"<<
b=200;
backdoorCall(b1);
}
friend int backdoorCall(Bank b1); getch(); return 0;
}; }