OOPs
OOPs
OOPs
Definition
Object-oriented programming or OOPs refers to the language that uses the concept of
class and object in programming. The main objective of OOPs is to implement real-world
entities such as polymorphism, inheritance, encapsulation, abstraction, etc. The main
aim of OOP is to bind together the data and the functions that operate on them so that
no other part of the code can access this data except that function.
Class
A class is a logical entity used to define a new data type. A class is a user-defined type
that describes what a particular kind of object will look like. Thus, a class is a template or
blueprint for an object. A class contains variables, methods, and constructors.
Classes are very useful in programming. Consider the example of where you don't want
to use just one car but 100 cars. Rather than describing each one in detail from scratch,
you can use the same car class to create 100 objects of the type 'car'. You still have to
give each one a name and other properties, but the basic structure of what a car looks
like is the same.
Object
An object is an instance of a Class. It is an identifiable entity with some characteristics
and behavior. Objects are the basic units of object-oriented programming. It may be any
real-world object like a person, chair, table, pen, animal, car, etc.
A simple example of an object would be a car. Logically, you would expect a car to have
a model number or name. This would be considered the property of the car. You could
also expect a car to be able to do something, such as starting or moving. This would be
considered a method of the car.
The class’s default constructor is called, and it dynamically allocates memory for one
object of the class. The address of the memory allocated is assigned to the pointer, i.e.,
objectName.
Constructor: - Constructors are special class functions that perform the initialization of
every object. In C++, the constructor is automatically called when an object is created. It
is a special method of the class because it does not have any return type. It has the
same name as the class itself.
Features of OOPs: -
Four major object-oriented programming features make them different from non-OOP
languages:
Abstraction is the property by virtue of which only the essential details are
displayed to the user.
Inheritance allows you to create class hierarchies, where a base class gives its
behavior and attributes to a derived class.
Polymorphism ensures that it will execute the proper method based on the
calling object’s type.
Encapsulation allows you to control access to your object’s state while making it
easier to maintain or change your implementation at a later date.
Access Specifier: -
Access Specifiers in a class are used to assign access to the class members. It sets some
restrictions on the class members from accessing the outside functions directly. Access
specifiers have a vital role in securing data from unauthorized access.
It allows us to determine which class members are accessible to other classes and
functions and which are not.
Public: All the class members with a public modifier can be accessed from
anywhere (inside and outside the class).
Private: All the class members with a private modifier can only be accessed by
the member function inside the class.
Protected: The access level of a protected modifier is within the class and outside
the class through child class (or subclass). If you do not make the child class, it
cannot be accessed outside the class.
Interview Questions
1. Why do we use OOPs?
2. What are the differences between the constructor and the method?
Constructor Method
It has the same name as the class It should have a different name than the
name. class name.
Class Object
Constructor-
A constructor is a special member function automatically called when an object is
created. In C++, the constructor is automatically called when an object is created. It is a
special class method because it does not have any return type. It has the same name as
the class itself.
A constructor initializes the class data members with garbage value if we don’t put any
value to it explicitly.
The constructor must be placed in the public section of the class because we want the
class to be instantiated anywhere. For every object in its lifetime constructor is called
only once at the time of creation.
Example:
class class_name{ int data_member1; string data_member2;
//creating constructor public: class_name(){ //
initialize data members with garbage value }};
Here, the function class_name() is a constructor of the class ‘class_name’. Notice that the
constructor
Types of Constructors:
There are three types of constructors in C++:
Default constructor
Parameterized Constructor
Copy Constructor
Default constructor: -
A constructor that doesn't take any argument or has no parameters is known as a
default constructor. In the example above, class_name() is a default constructor.
Parameterized Constructor: -
This is another type of Constructor with parameters. The parameterized constructor
takes its arguments provided by the programmer. These arguments help initialize an
object when it is created.
Copy Constructor: -
These are a particular type of constructor that takes an object as an argument and
copies values of one object’s data members into another object. We pass the class
object into another object of the same class in this constructor. As the name suggests,
you Copy means to copy the values of one Object into another Object of Class. This is
used for Copying the values of a class object into another object of a class, so we call
them Copy constructor and for copying the values.
Constructor Overloading: -
Constructor overloading can be defined as the concept of having more than one constructor with
different parameters so that every constructor can perform a different task.
Destructor: -
A destructor is a special member function that works just opposite to a constructor;
unlike constructors that are used for initializing an object, destructors destroy (or delete)
the object. The purpose of the destructor is to free the resources that the object may
have acquired during its lifetime.
Interview Questions: -
1. Does C++ compiler create a default constructor when we write our own?
In C++, compiler by default creates a default constructor for every class. But, if we
define our own constructor, compiler doesn’t create the default constructor.
this Pointer-
this pointer holds the address of the current object. In simple words, you can say that
this pointer points to the current object of the class.
Shallow Copy-
An object is created by simply copying the data of all variables of the original object. Here, the
pointer will be copied but not the memory it points to. It means that the original object and the
created copy will now point to the same memory address, which is generally not preferred.
Since both objects will reference the exact memory location, then change made by one will reflect
those change in another object as well. This can lead to unpleasant side effects if the elements of
values are changed via some other reference. Since we wanted to create an object replica, the
Shallow copy will not fulfill this purpose.
Deep Copy-
An object is created by copying all the fields, and it also allocates similar memory resources with the
same value to the object. To perform Deep copy, we need to explicitly define the copy constructor
and assign dynamic memory as well if required. Also, it is necessary to allocate memory to the other
constructors’ variables dynamically.
A deep copy means creating a new array and copying over the values.
Changes to the array values referred to will not result in changes to the array data refers to.
Interview Questions
1. What is this pointer?
this pointer is accessible only inside the member functions of a class and points to the
object which has called this member function.
Shallow Copy stores the references of objects Deep copy stores copies of the object’s value.
to the original memory address.
Shallow Copy reflects changes made to the Deep copy doesn’t reflect changes made to the
new/copied object in the original object. new/copied object in the original object.
Shallow Copy stores the copy of the original Deep copy stores the copy of the original object
object and points the references to the and recursively copies the objects as well.
objects.
Encapsulation-
Encapsulation refers to bundling data and the methods that operate on that data into a
single unit.
Encapsulation may also refer to a mechanism of restricting the direct access to some
components of an object, such that users cannot access state values for all of the
variables of a particular object. Encapsulation can be used to hide both data members
and data functions or methods associated with an instantiated class or object.
In other words: Encapsulation is about wrapping data and methods into a single class and
protecting it from outside intervention.
Abstraction-
Abstraction means providing only some of the information to the user by hiding its
internal implementation details.
Abstraction is selecting data from a larger pool to show only relevant details of the object
to the user. It helps in reducing programming complexity and efforts. It is one of the most
important concepts of OOPs.
Real-life example: When you send an email to someone, you just click send, and you get
the success message; what happens when you click send, how data is transmitted over
the network to the recipient is hidden from you (because it is irrelevant to you).
We can implement Abstraction in C++ using classes. The class helps us to group data
members and member functions using available access specifiers. A Class can decide
which data members will be visible to the outside world and not. Access specifiers are
the main pillar of implementing abstraction in C++. We can use access specifiers to
enforce restrictions on class members.
Advantages Of Abstraction
Only you can make changes to your data or function, and no one else can.
It makes the application secure by not allowing anyone else to see the
background details.
Increases the reusability of the code.
Avoids duplication of your code.
Inheritance-
Inheritance is one of the key features of Object-oriented programming in C++. It allows us
to create a new class (derived class) from an existing class (base class).
The derived class inherits the features from the base class and can have additional
features of its own.
Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code
functionality and fast implementation time.
Types of Inheritance-
C++ supports five types of inheritance they are as follows:
1. Single inheritance
In single inheritance, one class can extend the functionality of another class. There
is only one parent class and one child class in single inheritances.
2. Multilevel inheritance
When a class inherits from a derived class, and the derived class becomes the base
class of the new class, it is called multilevel inheritance. In multilevel inheritance,
there is more than one level.
3. Multiple inheritance
In multiple inheritance, a class can inherit more than one class. This means that a
single child class can have multiple parent classes in this type of inheritance.
4. Hierarchical inheritance
In hierarchical inheritance, one class is a base class for more than one derived
class.
5. Hybrid inheritance
Hybrid inheritance is a combination of more than one type of inheritance. For
example, A child and parent class relationship that follows multiple and
hierarchical inheritances can be called hybrid inheritance.
Polymorphism-
Polymorphism is considered one of the important features of Object-Oriented
Programming. Polymorphism is a concept that allows you to perform a single action in
different ways. Polymorphism is the combination of two Greek words. The poly means
many, and morphs means forms. So polymorphism means many forms.
Real-life example: A person at the same time can have different characteristics. Like a
man at the same time is a father, a husband, and an employee. So the same person
possesses different behavior in different situations. This is called polymorphism.
a) Function overloading:
When there are multiple functions in a class with the same name but different
parameters, these functions are overloaded. The main advantage of function overloading
is that it increases the program’s readability. Functions can be overloaded by using
different numbers of arguments or by using different types of arguments.
b) Operator Overloading:
C++ also provides options to overload operators. For example, we can make the operator
(‘+’) for the string class to concatenate two strings. We know that this is the addition
operator whose task is to add two operands. When placed between integer operands, a
single operator, ‘+,’ adds them and concatenates them when placed between string
operands.
Runtime polymorphism:
Runtime polymorphism is also known as dynamic polymorphism. Method overriding is a
way to implement runtime polymorphism.
Method overriding:
Method overriding is a feature that allows you to redefine the parent class method in the
child class based on its requirement. In other words, whatever methods the parent class
has by default are available in the child class. But, sometimes, a child class may not be
satisfied with parent class method implementation. The child class is allowed to redefine
that method based on its requirement. This process is called method overriding.
Interview Questions
1.What is Encapsulation in C++? Why is it called Data hiding?
The process of binding data and corresponding methods (behavior) into a single unit is called
encapsulation in C++.
In other words, encapsulation is a programming technique that binds the class members
(variables and methods) together and prevents them from accessing other classes. Thereby
we can keep variables and methods safes from outside interference and misuse.
If a field is declared private in the class, it cannot be accessed by anyone outside the class
and hides the fields. Therefore, Encapsulation is also called data hiding.
Abstraction Encapsulation
Abstraction is the method of hiding Encapsulation is the process of binding data members
unnecessary details from the necessary ones. and methods of a program together to do a specific
job without revealing unnecessary details.
Abstraction allows you to focus on what the Encapsulation enables you to hide the code and data
object does instead of how it does it. into a single unit to secure the data from the outside
world.
In abstraction, problems are solved at the While in encapsulation, problems are solved at the
design or interface level. implementation level.
b. Inheritance helps in code reusability in child class by inheriting behavior from the parent
class. On the other hand, polymorphism enables child class to redefine already defined
behavior inside parent class.
Without polymorphism, a child class can’t execute its own behavior.