Object Oriented Programming
Object Oriented Programming
paradigm to design a program using classes and objects. It simplifies the software development
and maintenance by providing some concepts defined below :
1.) Class : - it is a user-defined data type which defines its properties and its functions.
Class is the only logical representation of the data. For example, Human being is a
class. The body parts of a human being are its properties, and the actions performed by
the body parts are known as functions. The class does not occupy any memory space till
the time an object is instantiated.
Note: - When an object is created using a new keyword, then space is allocated for the
variable in a heap, and the starting address is stored in the stack memory. When an object is
created without a new keyword, then space is not allocated in the heap memory, and the object
contains the null value in the stack.
class go {
public:
int x;
go(int a){ x=a;} // parameterized constructor.
go(go &i){ x = i.x;} // copy constructor
};
4.) Destructor: - A destructor works opposite to the constructor . it destructs the objects of
classes. It can be defined only once in a class. Like constructors, it is invoked
automatically. A destructor is defined like a constructor. It must have the same name as
class, prefixed with a tilde sign (~).
Two types : - 1.) default destructor 2.) virtual destructor
class A{
public:
// constructor and destructor are called automatically, once the object is instantiated
A a;
A b;
}
/*
Output: Constructor in use
Constructor in use Destructor in use Destructor in use
*/
5.) ‘this’ Pointer: - this is a keyword that refers to the current instance of the class. There
can be 3 main uses of ‘this’ keyword: -
struct node{
int data; node *next;
node(int x){
this->data = x;
this->next = NULL;
}
6.) Inheritance : - it is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such a way, you can reuse, extend or modify
the attributes and behaviors which are defined in other classes.
Note : - In C++, the class which inherits the members of another class is called derived class
and the class whose members are inherited is called base class. The derived class is the
specialized class for the base class.
C++ Syntax : - class derived_class :: visibility-mode base_class;
visibility-modes= {private, protected, public}
Types of Inheritance : -
1. Single inheritance : When one class inherits another class, it is known as single level
inheritance
2. Multiple inheritance : Multiple inheritance is the process of deriving a new class that
inherits the attributes from two or more classes.
3. Hierarchical inheritance : Hierarchical inheritance is defined as the process of deriving
more than one class from a base class.
4. Multilevel inheritance : Multilevel inheritance is a process of deriving a class from
another derived class.
5. Hybrid inheritance : Hybrid inheritance is a combination of simple, multiple
inheritance and hierarchical inheritance. (virtual inheritance is solution for diamond
problem) .
7.) Access Specifiers IMP : - The access specifiers are used to define how functions and
variables can be accessed outside the class. There are three types of access specifiers:
1. Private: Functions and variables declared as private can be accessed only within the
same class, and they cannot be accessed outside the class they are declared.
2. Public: Functions and variables declared under public can be accessed from anywhere.
3. Protected: Functions and variables declared as protected cannot be accessed outside
the class except a child class. This specifier is generally used in inheritance.
Key Notes : -
● Deleteis used to release a unit of memory,delete[]is used to release an array.
● Virtual inheritance facilitates you to create only one copy of each object even if the object
appears more than one in the hierarchy.
● Function overloading:Function overloading is defined as we can have more than one version
of the same function. The versions of a function will have different signatures meaning that they
have a different set of parameters.
6.) Encapsulation : - It is the process of combining data and functions into a single
unit called class. In Encapsulation, the data is not accessed directly; it is accessed
through the functions present inside the class. In simpler words, attributes of the class
are kept private and public getter and setter methods are provided to manipulate these
attributes. Thus, encapsulation makes the concept of data hiding possible. (Data hiding:
a language feature to restrict access to members of an object, reducing the negative
effect due to dependencies. e.g. "protected", "private" feature in C++).
7.) Abstraction : - We try to obtain an abstract view, model or structure of a real life
problem, and reduce its unnecessary details. With the definition of properties of
problems, including the data which are affected and the operations which are identified,
the model abstracted from problems can be a standard solution to this type of problems.
It is an efficient way since there are nebulous real-life problems that have similar
properties. To hide data of class outside of class we use access specifier .
Data binding: Data binding is a process of binding the application UI and business
logic. Any change made in the business logic will reflect directly to the application UI.
8.) Polymorphism : - The word polymorphism means different forms. it is the ability to
present the same interface for differing underlying forms (data types). With
polymorphism, each of these classes will have different underlying data. A point shape
needs only two coordinates (assuming it's in a two-dimensional space of course). A
circle needs a center and radius. A square or rectangle needs two coordinates for the
top left and bottom right corners and (possibly) a rotation. An irregular polygon needs a
series of lines. Precisely, Poly means ‘many’ and morphism means ‘forms’.
Method Overloading : - Method overloading is a technique which allows you to have more
than one function with the same function name but with different functionality. Method
overloading can be possible on the following basis:
Example :
class Add {
public:
int add(int a,int b){return (a + b);}
int add(int a,int b,int c){ return (a + b + c);}
};
C++ Syntax (for class) : -
class student{
public:
int id; // data member
int mobile; string name;
Output : 5 9
Virtual Function IMP : - A virtual function is used to replace the implementation provided by
the base class. The replacement is always called whenever the object in question is actually of
the derived class, even if the object is accessed by a base pointer rather than a derived pointer.
1. A virtual function is a member function which is present in the base class and redefined
by the derived class.
2. When we use the same function name in both base and derived class,the function in
base class is declared with a keyword virtual.
3. When the function is made virtual, then C++ determines at run-time which function is to
be called based on the type of the object pointed by the base class pointer.Thus, by
making the base class pointer to point to different objects, we can execute different
versions of the virtual functions.
Key Points: -
1. Virtual functions cannot be static.
2. A class may have a virtual destructor but it cannot have a virtual constructor.
11.1) Friend Function : - Friend function acts as a friend of the class.It can access the private
and protected members of the class.The friend function is not a member of the class, but it must
be listed in the class definition. The non-member function cannot access the private data of the
class. Sometimes, it is necessary for the non-member function to access the data. The friend
function is a non-member function and has the ability to access the private data of the class.
Note :
1. A friend function cannot access the private members directly, it has to use an object
name and dot operator with each member name.
2. Friend function uses objects as arguments.
class A{
int a = 2; int b = 4;
public:
friend int mul(A k){ return (k.a * k.b);} // friend function
};
int main(){
A obj;
int res = mul(obj); cout << res << endl; } // 8
Note : - any entity reference.It is another way to reuse the class. It is a form of association
that represents the HAS-A relationship.
12.) Pure Virtual Function:
1. A pure virtual function is not used for performing any task. It only serves as a
placeholder.
2. A pure virtual function is a function declared in the base class that has no definition
relative to the base class.
3. A class containing the pure virtual function cannot create an object of this class
such classes are known as abstract base classes.
4. The main objective of the base class is to provide the traits to the derived classes and to
create the base pointer used for achieving the runtime polymorphism.
class Base{
public:
virtual void show() = 0;
};
13.) Abstract Classes / Interface: - In C++ class is made abstract by declaring at least one of
its functions as a pure virtual function. A pure virtual function is specified by placing "= 0" in its
declaration.Its implementation must be provided by derived classes.
// abstract class
class Shape{
public:
virtual void draw()=0;
};
class Rectangle : Shape{
public:
void draw(){cout << "Rectangle" << endl;}
};
Output :
Rectangle Square
13.) Shallow copy : - If we don’t define our own copy constructor, the C++ compiler creates a
default copy constructor for each class which does a memberwise copy between objects. The
compiler-created copy constructor works fine in general. We need to define our own copy
constructor only if an object has pointers or any runtime allocation of the resource like a file
handle, a network connection, etc.
The default constructor does only shallow copy.
Deep Copy : -
In a user-defined copy constructor, we make sure that pointers (or references) of copied objects
point to new memory locations.
#include<bits/stdc++.h>
using namespace std;
// user-defined namespace
namespace Add {
int a = 5, b = 5;
int add() {return (a + b);}
}
int main() {int res = Add :: add(); cout << res;} // accessing the function inside namespace
// output : 10
15.) Exception Handling : - Exception handling provides a way to transfer control from one
part of a program to another and can avoid the abrupt termination of the program.
C++ exception handling is built upon three keywords: try, catch, and throw.
1. throw − A program throws an exception when a problem shows up. This is done using a
throw keyword.
2. catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the catching of an
exception
3. try − A try block identifies a block of code for which particular exceptions will be activated.
It's followed by one or more catch blocks
int main() {
try {
In the above example we can see if the user enters n2 as 0, then we will throw an
exception and we can avoid abrupt termination of the program.