Final Unit-4, (Part-A) Notes of OOP (KOE-064) by Updesh Kumar
Final Unit-4, (Part-A) Notes of OOP (KOE-064) by Updesh Kumar
These include:
1. Objects
2. Classes
4. Inheritance
5. Polymorphism
6. Dynamic binding
7. Message passing
1-Objects: -
➢ 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.
➢ 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: -
➢ 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
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
“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.
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.
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.
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 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: -
So, we can also say, Polymorphism means the ability to take more than on form.
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
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;
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
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.
#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
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
#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:-
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.”
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,
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.
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.
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.
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.
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.
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.
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.
<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).
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.
#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
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
Features of destructor
Syntax of destructor
~classname()
{
......
}
Note: If you do not specify a destructor, the compiler generates a default destructor for you.
#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.
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.