Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

OOPs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

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.

When a class is defined, no memory is allocated, but memory is allocated when it is


instantiated (i.e., an object is created). For an empty class 1 byte size is allocated else
size is allocated according to data types.

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.

Syntax to define a class: -


class class_name{// class body //properties //methods};

Syntax to create an object in C++:


class_name objectName;

Syntax to create an object dynamically in C++:


class_name * objectName = new class_name();
Data Members: - The variables which are declared in any class by using any
fundamental data types (like int, char, float, etc.) or derived data types (like class,
structure, pointer, etc.) are known as Data Members.

Methods: - A method is the equivalent of a function in object-oriented programming that


is used inside classes. The methods are the actions that perform operations. A method
accepts parameters as arguments, manipulates these, and then produces an output
when the method is called on an object.

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.

Why do we need object-oriented programming?


 To make the development and maintenance of projects more effortless.
 To provide the feature of data hiding that is good for security concerns.
 We can solve real-world problems if we are using object-oriented programming.
 It ensures code reusability.
 It lets us write generic code: which will work with a range of data, so we don't

have to write basic stuff over and over again.

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.

There are three types of access modifiers available in C++:


 Public
 Private
 Protected

 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?

 It gives clarity in programming and allows simplicity in solving complex


problems.
 Data and code are bound together by encapsulation.
 Code can be reused, and it reduces redundancy.
 It also helps to hide unnecessary details with the help of Data Abstraction.
 Problems can be divided into subparts.
 It increases the readability, understandability, and maintainability of the
code.

2. What are the differences between the constructor and the method?

Constructor Method

It is a block of code that initializes a It is a group of statements that can be


newly created object. called at any point in the program using its
name to perform a specific task.

It has the same name as the class It should have a different name than the
name. class name.

It has no return type. It needs a valid return type if it returns a


value; otherwise void.

It is called implicitly at the time of It is called explicitly by the programmer by


object creation making a method call

If a constructor is not present, a In the case of a method, no default method


default constructor is provided by Java is provided.

3. What are the main features of OOPs?


 Inheritance
 Encapsulation
 Polymorphism
 Data Abstraction
4. The disadvantage of OOPs?

 Requires pre-work and proper planning.


 In certain scenarios, programs can consume a large amount of memory.
 Not suitable for a small problem.
 Proper documentation is required for later use.

5. What is the difference between class and structure?

Class: User-defined blueprint from which objects are created. It consists of


methods or sets of instructions that are to be performed on the objects.

Structure: A structure is basically a user-defined collection of variables of different


data types.

6. What is the difference between a class and an object?

Class Object

Class is the blueprint of an object. It is


An object is an instance of the class.
used to create objects.

No memory is allocated when a class is Memory is allocated as soon as an object


declared. is created.

An object is a real-world entity such as a


A class is a group of similar objects.
book, car, etc.

Class is a logical entity. An object is a physical entity.

Objects can be created many times as


A class can only be declared once.
per requirement.

Objects of the class car can be BMW,


An example of class can be a car.
Mercedes, Ferrari, etc.

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.

As there is a concept of function overloading, similarly constructor overloading is applied when we


overload a constructor more than a purpose.

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.

~class_name() { //Some code }

When is a destructor called?


A destructor function is called automatically when:
 the object goes out of scope
 the program ends
 a scope (the {} parenthesis) containing local variable ends.
 a delete operator is called
There cannot be more than one destructor in a class.
They do not have any return type, not even void. I
The programmer cannot access the address of the destructor.
When you do not specify any destructor in a class, the compiler generates a default
destructor and inserts it into your code.

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.

2. Explain constructor in C++


A constructor is a special member function automatically called when an object is
created. A constructor initializes the class data members with garbage value if we don’t
put any value to it explicitly.

3. What do you mean by constructor overloading?


The concept of having more than one constructor with different parameters to perform a
different task is known as constructor overloading.

4. Explain Destructor in C++


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.

5. What is a 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. In this constructor, we
pass the class object into another object of the same class.

6. How many types of constructors are there?


There are three types of constructors in C++:
 Default constructor
 Parameterized Constructor
 Copy Constructor

7. When should the destructor use delete to free the memory?


If the object is created by using new or the constructor uses new to allocate memory that
resides in the heap memory or the free store, the destructor should use delete to free the
memory.

8. What is the return type of constructor and destructor?


They have no return type, not even void.

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.

2. When is it necessary to use this pointer?


Suppose we have two local variables with the same names as the data members. Suppose
you want to assign the local variable value to the data members. In that case, you won’t be
able to do until unless you use this pointer because the compiler won’t know that you are
referring to the object’s data members unless you use this pointer.

3. What is similar between deep copy and shallow copy?


Both are used to copy data between objects.

1. What is the difference between deep copy and shallow copy?

Shallow Copy Deep Copy

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.

Shallow copy is faster. Deep copy is comparatively slower.

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.

There are two types of polymorphism in C++

Compile Time Polymorphism:


Compile-time polymorphism is also known as static polymorphism. This type of
polymorphism can be achieved through function overloading or operator overloading.

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.

2.What is the difference between Abstraction and Encapsulation?

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.

Achieved through encapsulation. You can implement encapsulation using Access


Modifiers (Public, Protected & Private.)

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.

3.How much memory does a class occupy?


Classes do not consume any memory. They are just a blueprint based on which objects are
created. When objects are created, they initialize the class members and methods and
therefore consume memory.

4.Are there any limitations of Inheritance?


Yes, with more powers comes more complications. Inheritance is a very powerful feature in
OOPs, but it also has limitations. Inheritance needs more time to process, as it needs to
navigate through multiple classes for its implementation. Also, the classes involved in
Inheritance - the base class and the child class, are very tightly coupled together. So if one
needs to make some changes, they might need to do nested changes in both classes.
Inheritance might be complex for implementation, as well. So if not correctly implemented, this
might lead to unexpected errors or incorrect outputs.

5.What is the difference between overloading and overriding?


Overloading is a compile-time polymorphism feature in which an entity has multiple
implementations with the same name—for example, Method overloading and Operator
overloading.
Whereas Overriding is a runtime polymorphism feature in which an entity has the same name,
but its implementation changes during execution. For example, Method overriding.

6.What are the various types of inheritance?


The various types of inheritance include:
Single inheritance
Multiple inheritances
Multi-level inheritance
Hierarchical inheritance
Hybrid inheritance

7.What are the advantages of Polymorphism?


There are the following advantages of polymorphism in C++:
a. Using polymorphism, we can achieve flexibility in our code because we can perform various
operations by using methods with the same names according to requirements.
b. The main benefit of using polymorphism is when we can provide implementation to an
abstract base class or an interface.

8.What are the differences between Polymorphism and Inheritance in C++?


The differences between polymorphism and inheritance in C++ are as follows:
a. Inheritance represents the parent-child relationship between two classes. On the other
hand, polymorphism takes advantage of that relationship to make the program more dynamic.

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.

You might also like