0% found this document useful (0 votes)
22 views33 pages

Final Unit-4, (Part-A) Notes of OOP (KOE-064) by Updesh Kumar

The document outlines the fundamental concepts of Object-Oriented Programming (OOP), including objects, classes, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. Each concept is explained in detail with examples in C++, highlighting their significance and application in programming. Key features such as data hiding and access control through access specifiers are also discussed.

Uploaded by

ananyasharma4014
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views33 pages

Final Unit-4, (Part-A) Notes of OOP (KOE-064) by Updesh Kumar

The document outlines the fundamental concepts of Object-Oriented Programming (OOP), including objects, classes, encapsulation, inheritance, polymorphism, dynamic binding, and message passing. Each concept is explained in detail with examples in C++, highlighting their significance and application in programming. Key features such as data hiding and access control through access specifiers are also discussed.

Uploaded by

ananyasharma4014
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

OOP Subject Unit-4 (Part-A) by Updesh Jaiswal

Basic Concepts of Object-Oriented Programming:

These include:

1. Objects

2. Classes

3. Data Encapsulation, Hiding and Abstraction

4. Inheritance

5. Polymorphism

6. Dynamic binding

7. Message passing

We will discuss these concepts one by one in detail here.

1-Objects: -

“Objects are the basic run time entities in an object-oriented system.”

➢ Objects may represent a person, a place, a bank account, a table of data or any item that
the program has to handle.
➢ Objects take up space in the memory and have an associated address like a Structure in C
or Record in Pascal.
➢ Each object contain data, and code to manipulate data.

➢ Programming problem is analyzed in term of objects and the nature of communication


between them. Program objects should be chosen such that they match closely with the
real-world objects.

➢ When a program is executed, the objects interact by sending messages to one another.
For example, if “customer” and “account” are two objects in a program, then the
customer object may send a message to the account object requesting for the bank
balance.
➢ Objects can interact without having to know details of each other’s data or code.
Example of an object STUDENT is given in figure 1:

2-Classes: -

“A class is a collection of objects of similar types”.

➢ The entire set of data and code of an object can be made a user-defined data type with the
help of class.
➢ In fact, objects are variables of the type class.
➢ Once a class has been defined, we can create any number of objects belonging to that
class.
➢ Each object is associated with the data of type class with which they are created.
For examples, Mango, Apple and Orange are members of class Fruit.
If fruit has been defined as a class, then the statement:
Fruit Mango; will create an object Mango belonging to the class Fruit.

Syntax to declare a Class

Syntax

class Class_Name
{
data member;
method member;
} ;
Simple Example of an Object and Class using a C++ Program

In this example, we have created an Employee class that have two data members: eid and
ename. We are creating the object of the Employee class and printing the object values.

Example

#include<iostream.h>
#include<conio.h>
using namespace std;
class Employee
{
public:
int salary // data member
void sal()
{
cout<<"Enter salary: ";
cin>>salary;
cout<<"Salary: "<<salary;
}
};
void main()
{
Employee e; //creating an object of Employee
e.sal();
getch();
}

Output

Enter salary: 4500


Salary: 4500
3-Data Encapsulation, Hiding and Abstraction: -
Encapsulation in C++

“The wrapping up of data and function into a single unit (called class) is known as
encapsulation.”

Data Encapsulation is the most striking feature of a class. The data is not accessible to the
outside world, and only those functions which are wrapped in the class can access it. These
functions provide the interface between the object’s data and the program.

The insulation of the data from direct access by the program is called data hiding or
information hiding.

Real Life Example of Encapsulation in C++

The common real-life example of encapsulation is a Capsule. In capsule many types of


medicines are encapsulated inside the wrapper of the capsule.

Similarly in C++programming, data members (variables) and member functions (methods or


procedure) are encapsulated in the body of a class (wrapper).
Benefits of Encapsulation-

i. Provides abstraction between an object and its clients.


ii. Protects an object from unwanted access by clients.

C++ supports the properties of encapsulation and data hiding through the creation of user-
defined data types, called classes.
A class can contain private, protected and public members. By default, all items defined in a
class are private.

There are 3 access specifiers or access modifiers or access control in C++:


public - members are accessible from outside the class.
private - members cannot be accessed (or viewed) from outside the class.
protected - members cannot be accessed from outside the class, however, they can be accessed
in inherited classes.
Note: Access modifiers are used to implement an important aspect of Object-Oriented
Programming known as Data Hiding.
Example of Encapsulation and Data Hiding by a C++ program:

class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

The variables length, breadth, and height are private. This means that they can be accessed only by
members of the Box class, and not by any other part of your program. This is one way
encapsulation is achieved.
Abstraction in C++

“Abstraction means displaying only essential information and hiding the details”.

➢ Data abstraction refers to providing only essential information about the data to the
outside world, and hiding the background details or implementation.
➢ Abstraction is the concept of exposing only the required essential characteristics and
behavior with respect to a context.
➢ Hiding of data is involved in data abstraction. In object-oriented programming language
this is implemented automatically while writing the code in the form of class and object.
➢ Data abstraction can be used to provide security for the data from the unauthorized
methods.
➢ In C++ language, data abstraction can be achieved by using class.

Real life example of Abstraction

Abstraction shows only important things to the user and hides the internal details.

For example: when we ride a car, we only know about how to ride a car but can not know
about how it works? And also, we do not know internal functionality of a car.
Example of Abstraction and Data Hiding in C++

#include<iostream.h>
#include<conio.h>
using namespace std;
class sum
{
// hidden data from outside world
private: int a,b,c;

public:
void add()
{
clrscr();
cout<<"Enter any two numbers: ";
cin>>a>>b;
c=a+b;
cout<<"Sum: "<<c;
}
};
void main()
{
sum s;
s.add();
getch();
}

Output
Enter any two numbers:
4
5
Sum: 9

4-Inheritance: -

“Inheritance is the process by which objects of one class acquired the properties
of objects of another classes”.

“The capability of a class to derive properties and characteristics from another class is called
Inheritance”.

➢ Inheritance supports the concept of hierarchical classification.

➢ Inheritance is one of the most important features of Object-Oriented Programming.

➢ Inheritance is a feature or a process in which, new classes are created from the existing
classes.

➢ In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it. This is possible by
deriving a new class from the existing one. The new class will have the combined feature
of both the classes.
➢ The new class created is called “derived class” or “child class” and the existing class is
known as the “base class” or “parent class”. The derived class now is said to be inherited
from the base class. When we say derived class inherits the base class, it means, the
derived class inherits all the properties of the base class, without changing the properties
of base class and may add new features to its own. These new features in the derived
class will not affect the base class. The derived class is the specialized class for the base
class.

Sub Class: The class that inherits properties from another class is called Subclass or Derived
Class or child class.
Super Class: The class whose properties are inherited by a subclass is called Base Class or
Superclass or parent class.
For example, the bird ‘robin’ is a part of class ‘flying bird’ which is again a part of the class
‘bird’.
The principal behind this sort of division is that each derived class shares common
characteristics with the class from which it is derived as illustrated in Figure 2.

The real appeal and power of the inheritance mechanism is that it allows the programmer to
reuse and tailor the class in such a way that it does not introduce any undesirable side-effects
into the rest of classes.
Note: The examples programs of all type of Inheritance are given in another part of my
Notes/PPTs. Read those also. 👍🏻
5- Polymorphism: -

Polymorphism is derived from two Greek words: poly and morphs.

The word "poly" means many and “morphs” means forms.

So, we can also say, Polymorphism means the ability to take more than on form.

Real life example of Polymorphism in C++


Suppose if you are in class room that time you behave like a student, when you are in market
at that time you behave like a customer, when you at your home at that time you behave like a
son. Here one person has different-different behaviors so concept of Polymorphism exists.

Type of Polymorphism in C++: -

i. Compile time polymorphism (Static polymorphism)


ii. Run time polymorphism (Dynamic polymorphism)
i- Compile time Polymorphism
In C++ programming you can achieve compile time polymorphism (Early Binding) in two
ways, which are given below;

a) Method overloading
b) Operator overloading

a) Method Overloading
Whenever same method name is exiting multiple times in the same class with different
number of parameter or different order of parameters or different types of parameters is known
as method overloading or function overloading or Procedure overloading.
In below example program method "sum()" is present in Addition class with same name but
with different signatures or arguments.
Example of Method Overloading in C++

#include<iostream.h>
using namespace std;
class Addition
{
public:
void sum(int a, int b)
{
cout<<a+b;
}
void sum(int a, int b, int c)
{
cout<<a+b+c;
}
};
void main()
{
clrscr();
Addition obj;
obj.sum(10, 20); //Early Binding Occurs
cout<<endl;
obj.sum(100, 200, 300); //Early Binding Occurs
}

Output

30 600

b)- Operator Overloading

Operator overloading is possible in C++, you can change the behaviour of an operator like +,
-, etc to do different things. Operator overloading is sometimes referred to as ad-hoc
polymorphism too.

So, a single operator ‘+’, when placed between two integer operands, adds them and when
placed between two string operands, concatenates them. Consider two strings s1 and s2, we
can concatenate two strings s1 and s2 by overloading + operator as String s, s = s1 + s2;
An Example program for Operator overloading:

We know that ++x increments the value of x by 1. If we want to overload this and increase the
value by 100. The program below does that:

#include <iostream>
using namespace std;
class Test
{
private:
int count;
public:
Test( ): count(256)
{
//writing function name followed by data member and passed on value works like constructor
// Test(): count(101) same as writing count = 101; here
}
// we write operator before overloading such operators
void operator ++( )
{
count = count+100;
}

void Display( )
{
court << "Count: " << count;
}
};

int main( )
{
Test t;

// this calls function “void operator ++()"


++t;

t.Display( );

return 0;
}

Output
257
ii- Run time Polymorphism

In C++ programming you can achieve Run time polymorphism (Late Binding) in two ways,
which are given below;

a) Function Overriding
b) Virtual Function

a) Function Overriding in C++


Define any method in both base class and derived class with same name, same parameters or
signature, this concept is known as Function Overriding or Method Overriding or Procedure
Overriding.

It is a case when a function is declared with same name in both the parent class (Base Class)
and child class (Derived Class). To decide upon which function has to be called, the program
will only know at the run time (it is known as Late Binding).

In below example same method "show()" is present in both base and derived class with same
name and signature.

Example of Method Overriding in C++

#include<iostream.h>
#include<conio.h>
using namespace std;
class Base
{
public:
void show()
{
cout<<"Base class";
}
};
class Derived:public Base
{
public:
void show()
{
cout<<"Derived Class";
}
}

int mian()
{
Base b; //Base class object
Derived d; //Derived class object
b.show();
d.show(); //Late Binding Occurs
getch();
}

Output

Base class
Derived Class

Note: Polymorphism (Method Overriding) is extensively used in implementing


inheritance.
Figure 3, illustrates that a single function name Draw ( ) is used in base class and derived
classes to handle different number and different types of argument. Using a single function
name to perform different type of task is known as Method Overriding.
b) Virtual Function: in C++

A virtual function is a member function of a class that is declared within a base class and
re-defined in derived class.

When you want to use same function name in both the base and derived class, then the function
in base class is declared as virtual by using the virtual keyword and again re-defined this
function in derived class without using virtual keyword.

Syntax

virtual return_type function_name( )


{
.........................
.........................
}

Virtual Function Example in C++

#include<iostream.h>
#include<conio.h>
class A
{
public:
virtual void show()
{
cout<<"Hello base class";
}
};
class B : public A
{
public:
void show()
{
cout<<"Hello derived class and function is redefined here";
}
};
void main()
{
clrscr();
A aobj;
B bobj;
A *bptr;
bptr=&aobj;
bptr->show(); // call base class function
bptr=&bobj;
bptr->show(); // call derive class function
getch();
}

Output:-

Hello base class


Hello derived class and function is redefined here

6-Dynamic Binding:-

Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
“Dynamic binding means that the code associated with a given procedure call is not known
until the time of the call at run time.”

Dynamic binding is associated with polymorphism and inheritance.


A function call associated with a polymorphic reference depends on the dynamic type of that
reference.
Consider the procedure “draw” in above Figure 3 in which by inheritance; every object will
have this procedure. Its algorithm is, however, unique to each object and so the draw procedure
will be redefined in each class that defines the object. At run-time, the code matching the object
under current reference will be called.

7- Message Passing: -

An object-oriented program consists of a set of objects that communicate with each other. The
process of programming in an object-oriented language, involves the following basic steps:
a) Creating classes that have data members and member functions,

b) Creating objects from class definitions,

c) Establishing communication among objects.

➢ Message passing (communication) in C++ is the exchange of information between two


or more objects via a logical entity known as a message.
➢ Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another.
➢ A Message for an object is a request for execution of a procedure, and therefore will
invoke a function (procedure or method) in the receiving object that generates the
desired results.
Message passing in C++ involves specifying the name of object, the name of the function and
the information to be sent.
Access Control or Access Modifiers or Access Specifiers in Classes-
Access specifiers in C++ class define the access control rules. For this purpose, C++ has
introduced three keywords, namely:

1. public
2. private
3. protected

These access specifiers are used to set boundaries for availability of members of class to it data
members or member functions.

Access specifiers in the program are followed by a colon (:).

You can use either one, two or all three specifiers in the same class to set different boundaries
for different class members.

Public-

Public, means all the class members declared under public will be available to everyone. The
data members and member functions declared public can be accessed by other classes too.
Hence there are chances that they might change them. So, the key members must not be
declared public. An example showing public access is given below:

class PublicAccessIsUsed
{
public: // public access specifier
int x; // Data Member Declaration
void display(); // Member Function declaration
}
Private-

Private keyword, means that no one can access the class members declared private outside that
class. If someone tries to access the private member, they will get a compile time error. By
default, class variables and member functions are private.

An example showing private access is given below:

class PrivateAccessIsUsed
{
private: // private access specifier
int x; // Data Member Declaration
void display(); // Member Function declaration
}

Protected-

Protected is the last access specifier and it is similar to private, so, it makes class member
inaccessible outside the class but they can be accessed by any subclass of that class.

If class A is inherited by class B, then class B is subclass of base class A.

An example showing protected access is given below:

class ProtectedAccessIsUsed
{
protected: // protected access specifier
int x; // Data Member Declaration
void display(); // Member Function declaration
}
Friend Function in C++
➢ In C++ a Friend Function that is a "friend" of a given class is allowed access to private
and protected data in that class.
➢ A friend function is a function that isn't a member of a class but has access to the class's
private and protected members. Friend functions aren't considered class members; they're
normal external functions that are given special access privileges.
➢ A function can be made a friend function using keyword friend. So, any friend function
is preceded with friend keyword. The declaration of friend function should be made
inside the body of a class (can be anywhere inside class either in private or public
section) starting with keyword friend.

Importance or Need or Advantages of Friend Function in C++

i. You do not access private or protected data member of any class, to access private and
protected data member of any class you need a friend function.
ii. Friend Function allows the sharing of private class information by a non-member
function.
iii. Friend Function accesses the non-public members of a class easily. It is widely used in
cases when two or more classes contain the interrelated members relative to other parts of
the program.
iv. The function is not in the scope of the class to which it has been declared as a friend.

Syntax of writing the Friend Function:

class class_name
{
......
friend returntype function_name(arguments);
};
Example of Friend function in C++

In below example program, you can access private function of class employee by using a
friend function.

#include<iostream.h>
#include<conio.h>

class employee
{
private:
friend void sal();
};

void sal()
{
int salary=4000;
cout<<"Salary: "<<salary;
}

void main()
{
employee e;
e.sal();
getch();
}

Output

Salary: 4000
Friend Class in C++

Similarly, like, friend function, a class can be also made a friend of another class using keyword
friend.

Syntax

class ClassB;

class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
... .. ...
}

class ClassB {
... .. ...
}

When a class is made a friend class, all the member functions of that class become friend
function.

If B is declared friend class of A, then, all member functions of class B can access private and
protected data of class A but, member functions of class A cannot access private and protected
data of class B. It is because friend relation in C++ is only granted, not taken.

Note: Remember, friendship relation in C++ is always granted not taken.

Constructor in C++
A Constructor is a special member function which will be called implicitly (automatically)
whenever an object of class is created.

Constructors are methods that are automatically executed every time you create an object.
Constructor in C++ is a special method that is invoked automatically at the time of object
creation. It is used to initialize the data members of new objects generally. The constructor in
C++ has the same name as the class. It constructs the values i.e. provides data for the object
which is why it is known/called as a constructor.

Features of Constructor

1) Constructor is a member function of a class, whose name is the same as the class name.
2) Constructor is a special type of member function that is used to initialize the data
members for an object of a class automatically when an object of the same class is
created. So, a constructor gets called automatically when we create the object of the
class.
3) Constructors do not return value; hence they do not have a return type.
4) Constructors can be overloaded.
5) A constructor can not be declared virtual.

Syntax of Constructors in C++

<class-name> (list-of-parameters)
{
// constructor definition
}

Note: If you do not specify a constructor, the compiler generates a default constructor for you
(expects no parameters and has an empty body).

Why use constructor??

The main use of constructor is placing user defined values in place of default values.
How Constructor eliminate default values??

Constructor are mainly used for eliminate default values by user defined values, whenever we
create an object of any class then it allocates memory for all the data members and initialize
their default values. To eliminate these default values by user defined values we use
constructor.

Example of Constructor in C++

#include<iostream.h>
#include<conio.h>
class sum
{
int a,b,c;
sum()
{
a=10;
b=40;
c=a+b;
cout<<"Addition is done by using constructor and result is:"<<c;
}
};
void main()
{
sum s;
getch();
}

Output

Addition is done by using constructor and result is: 50

In above example when we create an object “s” of "Sum" class then constructor of this class call
and initialize user defined value in a=10 and b=40. And here we no need to call sum() method.
Destructor

Destructor is a member function which deletes an object. A destructor function is called


automatically when the object goes out of scope:

When destructors are called?

• when program ends


• when a block containing temporary variables ends
• when a delete operator is called

Features of destructor

1) The same name as the class but is preceded by a tilde (~)


2) no arguments and return no values

Syntax of destructor

~classname()
{
......
}

Note: If you do not specify a destructor, the compiler generates a default destructor for you.

Example of Destructor in C++

#include<iostream.h>
#include<conio.h>
class sum
{
int a,b,c;
sum()
{
a=10;
b=20;
c=a+b;
cout<<"Sum: "<<c;
}
~sum()
{
cout<<<<endl;"call destructor";
}
delay(500);
};
void main()
{
sum s;
cout<<<<endl;"call main";
getch();
}

Output

Sum: 30
call main
call destructor

Explanation: In above example when you create an object s of class sum auto constructor of
class is call and after that control goes inside main and finally, before end of program destructor
is call.
Copy constructor:

A copy constructor is a special constructor in the C++ programming language for creating a
new object as a copy of an existing object.

➢ A copy constructor is a member function that initializes an object using another object
of the same class.
➢ In simple terms, a constructor which creates an object by initializing it with an object of
the same class, which has been created previously is known as a copy constructor.
➢ Copy constructor is used to initialize the members of a newly created object by
copying the members of an already existing object.
➢ Copy constructor takes a reference to an object of the same class as an argument.
➢ The process of initializing members of an object through a copy constructor is known as
copy initialization.
Example:

Sample(Sample &t)
{
id=t.id;
}
Object-oriented programming (OOP)
Object-oriented programming (OOP) is a style of programming characterized by the
identification of classes of objects closely linked with the methods (functions) with which they
are associated.
OOP is a programming paradigm that is based on the concept of “objects,” and “class”.
Benefits of OOP or Advantages of OOP in C++
1. Through inheritance, we can eliminate redundant code extend the use of existing Classes.

2. We can build programs from the standard working modules that communicate with one
another can leads to saving of development time and higher productivity.

3. The principle of data hiding helps the programmer to build secure program.

4. The OOP provides reusability to the code and extends the usage of the existing classes.

5. Object-oriented programming makes it easy to maintain any particular code as there are
objects and classes. There is no need to restructure the code.

6. Object-oriented programming provides the ability to simulate real-world events much


more effectively.

7. It is possible to have multiple instances of an object to co-exist without any interference.

8. Object-oriented system can be easily upgraded from small to large system.

9. Message passing techniques for communication between objects makes to interface


descriptions with external systems much simpler.

10.Software complexity can be easily managed.

Drawbacks of OOP or Disadvantages of OOP in C++

1. As OOP programs are large, they need more time to run, resulting in slower execution.
2. OOP is not a universal language, so we can only use it in some places. It is only used
when necessary. It is not appropriate for all sorts of issues.
3. Everything is represented as an object in OOP, so before applying it, we need to think
about objects well.

You might also like