Oops

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Best 30 OOPs Interview Questions with Answers

1. What is Object Oriented Programming (OOPs)?


Object Oriented Programming (also known as OOPs) is a programming paradigm where the complete
software operates as a bunch of objects talking to each other. An object is a collection of data and
the methods which operate on that data.
OR
OOP (Object-Oriented Programming) is a way of organizing code around objects, which represent
real-world things. These objects have properties (data) and actions (functions). OOP makes
programming simpler by using concepts like classes, inheritance, and encapsulation to keep code
modular and reusable.
My definition :- oops is about creating objects that contains both data and function or we can say
oops is a way of organizing code around objects , which represents real-world things.
REAL WORLD EXAMPLES:-
Here are some simple real-world examples of OOP:
1. Car (Object):
o Class: "Car" defines a blueprint with properties like color, brand, and model, and
actions like drive or honk.
o Objects: A red Toyota and a blue Honda are specific cars (objects) created from the
Car class, each with different properties but sharing similar actions.

"Think of a Class like a blueprint for a car. It defines what features the car should have (like
color, brand, and model) and what it can do (like drive or honk). But the blueprint itself is
not a real car — it’s just a design.
When you use that blueprint to create actual cars, those are called Objects. For example, a
red Toyota and a blue Honda are both real cars (objects) made from the same blueprint
(class). They have different properties (colors and brands) but can perform the same actions
(drive and honk)."

2. Animal (Object):
o Class: "Animal" defines properties like species and age, and actions like eat or sleep.
o Objects: A cat and a dog are objects of the Animal class, with both able to eat but
might do it in different ways (polymorphism).

"Imagine the Class 'Animal' as a general blueprint for all animals. It defines basic features like species
and age, and actions like eat and sleep. But the class itself is not a real animal; it's just the design.
When you create specific animals from that blueprint, like a cat or a dog, those are objects of the
Animal class. Both can perform the same actions, like eating or sleeping, but they might do it in
different ways. For example, a cat eats quietly, while a dog might eat noisily — this difference in
behavior for the same action is called polymorphism."
3. Bank Account (Object):
o Class: "Bank Account" defines a blueprint with properties like balance and account
number, and actions like deposit or withdraw.
o Objects: Your savings account and checking account are specific objects of the Bank
Account class, both handling money but possibly having different rules for interest or
withdrawal.
These examples show how OOP mirrors real-world concepts by organizing code around things
(objects) and their behavior

2. Why OOPs?
The main advantage of OOP is better manageable code that covers the following:
• Reusability: You can create a class once and reuse it in many places, which saves time and
effort.
• Organization: OOP keeps code clean and easy to understand by grouping related data and
actions into objects, making the program more structured.
• Maintenance: It’s easier to update and maintain code because each part is separated into
objects, and changes in one place won’t break the entire system.
• OOPS is faster & easier to excute.
3. What is a Class?
• A class is a building block of Object Oriented Programs. It is a user-defined data type that
contains the data members and member functions that operate on the data members. It is
like a blueprint or template of objects having common properties and methods.

• Class are a blueprint or a set of instruction to build a specify type of object.

• In oops , a class is a blueprint or template for creting objects . It defines the


properties(attributes/methods) and behaviour(methods/function) that object of that class
will have.

• Class is a user- defined data type , which holds its own data members and member function ,
which can be accessed and used by creating and instance of that class.

4. What is an Object?
An object is an instance of a class. Data members and methods of a class cannot be used directly. We
need to create an object (or instance) of the class to use them. In simple terms, they are the actual
world entities that have a state and behavior.
5. What are the main features of OOPs?
The main feature of the OOPs, also known as 4 pillars or basic principles of OOPs are as follows:
1. Encapsulation
2. Data Abstraction
3. Polymorphism
4. Inheritance

OOPs Main Features


6. What is Encapsulation?
Encapsulation is the binding of data and methods that manipulate them into a single unit is called
class such that the sensitive data is hidden from the users
It is implemented as the processes mentioned below:
1. Data hiding: A language feature to restrict access to members of an object. For example,
private and protected members in C++.
2. Bundling of data and methods together: Data and methods that operate on that data are
bundled together. For example, the data members and member methods that operate on
them are wrapped into a single unit known as a class.
7. What is Abstraction?
Abstraction is similar to data encapsulation and is very important in OOP. It means showing only the
necessary information and hiding the other irrelevant information from the user. Abstraction is
implemented using classes and interfaces.

Abstraction in C++ can be implemented using abstract classes or interfaces. An abstract class is a
class that contains at least one pure virtual function. A pure virtual function is a function that has no
implementation in the base class and must be overridden in the derived class.
Explanation:
1. Abstract Class:
o The class Shape is an abstract class because it has a pure virtual function draw() = 0.
o This means we cannot create an object of Shape directly.
2. Derived Classes:
o Classes Circle and Rectangle are derived from Shape and both override the draw()
method to provide their specific implementations.
3. Abstraction:
o The concept of abstraction is implemented here, as the Shape class defines the
general structure (through the pure virtual function draw()), but the specific details
(what shape to draw) are handled by the derived classes (Circle and Rectangle).
In this way, abstraction allows us to hide the details of what kind of shape we are drawing, focusing
only on the concept of "drawing" from the user's perspective.
NOTE:-
A pure virtual function is a function declared in a class that has no implementation in that class.
Instead, it serves as a placeholder that must be defined in any derived class. It’s used to create an
abstract class, which cannot be instantiated directly.
Simple Definition:
A pure virtual function is a function that:
• Is declared in a class with = 0 at the end.
• Requires derived classes to provide their own version of that function
8. What is Polymorphism?
Polymorphism can be classified into two types based on the time when the call to the object or
function is resolved. They are as follows:
1. Compile Time Polymorphism
2. Runtime Polymorphism

The word “Polymorphism” means having many forms. It is the property of some code to behave
differently for different contexts. For example, in C++ language, we can define multiple functions
having the same name but different working depending on the context.
Polymorphism can be classified into two types based on the time when the call to the object or
function is resolved. They are as follows:
• Compile Time Polymorphism
• Runtime Polymorphism
A) Compile-Time Polymorphism
Definition: Compile-time polymorphism (also known as static polymorphism) occurs when the method to be
executed is determined at compile time. This is usually achieved through function overloading and operator
overloading.
Key Features:
• The decision about which function to call is made during compilation.
• Functions can have the same name but differ in the type or number of parameters.

Compile-time Polymorphism: Achieved through function overloading and operator overloading.


B) Runtime Polymorphism
Run-Time Polymorphism
Definition: Run-time polymorphism (also known as dynamic polymorphism) occurs when the method
to be executed is determined at run time. This is achieved using inheritance and virtual functions.
Key Features:
• The decision about which function to call is made during program execution.
• It allows for overriding methods in derived classes.

NOTE:-
can we implement without using the base class pointer
Yes, you can implement run-time polymorphism without explicitly using a base class pointer.
However, the core concept of run-time polymorphism typically involves base and derived class
relationships. That said, you can achieve polymorphic behavior through other means, such as using
references or through other design patterns (like interfaces or function pointers).
Using Base Class References
Instead of using a base class pointer, you can use a reference to the base class to achieve run-time
polymorphism. Here’s an example:
In C++, run-time polymorphism typically requires inheritance and virtual functions because they
allow for method overriding in derived classes, enabling different behaviors at runtime based on the
object type.
However, if you want to achieve similar behavior without traditional inheritance and virtual
functions, you can use other techniques such as:
1-> Function pointer
2-> lamda functions
9. What is Inheritance? What is its purpose?
The idea of inheritance is simple, a class is derived from another class and uses data and
implementation of that other class. The class which is derived is called child or derived or subclass
and the class from which the child class is derived is called parent or base or superclass.
The main purpose of Inheritance is to increase code reusability. It is also used to achieve Runtime
Polymorphism.
10. What are access specifiers? What is their significance in OOPs?
Access specifiers are special types of keywords that are used to specify or control the accessibility of
entities like classes, methods, and so on. Private, Public, and Protected are examples of access
specifiers or access modifiers.
The key components of OOPs, encapsulation and data hiding, are largely achieved because of these
access specifiers.
In simple terms, access specifiers in C++ are used to control who can access the members (variables
and methods) of a class. They help in restricting or allowing access to certain parts of a class to
ensure security and proper usage.
There are three types of access specifiers:
1. Public:
o Anything declared as public can be accessed from anywhere in the program.
o This means you can use public members both inside and outside of the class.

2. Private:
o Anything declared as private can only be accessed from within the class itself. o This
is useful when you want to hide the internal details and keep things safe from being
changed accidentally outside the class.
Protected:
o Anything declared as protected can be accessed within the class and by derived
classes (classes that inherit from the parent class).
o It's similar to private, but it allows child classes to use the protected members.

Quick Summary:
• Public: Accessible from anywhere.
• Private: Only accessible within the class.
• Protected: Accessible within the class and derived classes (inheritance).
These access specifiers are key to implementing encapsulation in object-oriented programming,
which helps in protecting data and controlling how it is accessed or modified.
11. What are the advantages and disadvantages of OOPs?

Advantages of OOPs Disadvantages of OOPs

The programmer should be well-skilled and should


OOPs provides enhanced code have excellent thinking in terms of objects as
reusability. everything is treated as an object in OOPs.

The code is easier to maintain and Proper planning is required because OOPs is a little bit
update. tricky.

It provides better data security by


restricting data access and avoiding OOPs concept is not suitable for all kinds of problems.
unnecessary exposure.

Fast to implement and easy to redesign


The length of the programs is much larger in
resulting in minimizing the complexity of
comparison to the procedural approach.
an overall program.

12. What other paradigms of programming exist besides OOPs?


The programming paradigm is referred to the technique or approach of writing a program. The
programming paradigms can be classified into the following types:
1. Imperative Programming Paradigm
It is a programming paradigm that works by changing the program state through assignment
statements. The main focus in this paradigm is on how to achieve the goal. The following
programming paradigms come under this category:
1. Procedural Programming Paradigm: This programming paradigm is based on the procedure
call concept. Procedures, also known as routines or functions are the basic building blocks of
a program in this paradigm.
2. Object-Oriented Programming or OOP: In this paradigm, we visualize every entity as an
object and try to structure the program based on the state and behavior of that object.
3. Parallel Programming: The parallel programming paradigm is the processing of instructions
by dividing them into multiple smaller parts and executing them concurrently.
2. Declarative Programming Paradigm
Declarative programming focuses on what is to be executed rather than how it should be executed. In
this paradigm, we express the logic of a computation without considering its control flow. The
declarative paradigm can be further classified into:
1. Logical Programming Paradigm: It is based on formal logic where the program statements
express the facts and rules about the problem in the logical form.
2. Functional Programming Paradigm: Programs are created by applying and composing
functions in this paradigm.
3. Database Programming Paradigm: To manage data and information organized as fields,
records, and files, database programming models are utilized.
13. What is the difference between Structured Programming and Object Oriented Programming?
Structured Programming is a technique that is considered a precursor to OOP and usually consists of
well-structured and separated modules. It is a subset of procedural programming. The difference
between OOPs and Structured Programming is as follows:

Object-Oriented Programming Structural Programming

A program’s logical structure is provided


Programming that is by structural programming, which
objectoriented is built on objects divides programs into their
having a state and behavior. corresponding functions.

It follows a bottom-to-top
It follows a Top-to-Down approach.
approach.
Restricts the open flow of data to
No restriction to the flow of data.
authorized parts only providing
Anyone can access the data.
better data security.

Enhanced code reusability due to


Code reusability is achieved by using
the concepts of polymorphism and
functions and loops.
inheritance.

Object-Oriented Programming Structural Programming

Methods work dynamically, making


calls based on object behavior and Functions are called sequentially, and
the need of the code at runtime. code lines are processed step by step.

Modifying and updating the code Modifying the code is difficult as


is easier. compared to OOPs.

Data is given more importance in


Code is given more importance.
OOPs.

14. What are some commonly used Object Oriented Programming Languages?
OOPs paradigm is one of the most popular programming paradigms. It is widely used in many
popular programming languages such as:
• C++
• Java
• Python
• JavaScript
• C#
• Ruby
16. What is the difference between overloading and overriding?
A compile-time polymorphism feature called overloading allows an entity to have numerous
implementations of the same name. Method overloading and operator overloading are two
examples.

Overloading means creating multiple functions with the same name but different parameters, either
in number or type. The compiler decides which function to call based on the arguments passed
Overriding is a form of runtime polymorphism where an entity with the same name but a different
implementation is executed. It is implemented with the help of virtual functions.

Overriding: Same function name and parameters, different implementations in base and derived
classes (resolved at runtime).
Explanation:
• Base class Vehicle: Defines a general method startEngine().
• Derived class Car: Overrides the startEngine() method to provide a car-specific behavior.
• Derived class Motorcycle: Also overrides startEngine() with motorcycle-specific behavior.
• We use a pointer to the base class (Vehicle*) to achieve runtime polymorphism, allowing
the function call to be resolved at runtime based on the actual object type.

17. Are there any limitations on Inheritance?


Yes, there are more challenges when you have more authority. Although inheritance is a very strong
OOPs feature, it also has significant drawbacks.
• As it must pass through several classes to be implemented, inheritance takes longer to
process.
• The base class and the child class, which are both engaged in inheritance, are also closely
related to one another (called tightly coupled). Therefore, if changes need to be made, they
may need to be made in both classes at the same time.
• Implementing inheritance might be difficult as well. Therefore, if not implemented correctly,
this could result in unforeseen mistakes or inaccurate outputs.

18. What different types of Inheritance are there?


Inheritance can be classified into 5 types which are as follows:

• Single Inheritance: A derived class inherits from one base class.


• Multiple Inheritance: A derived class inherits from more than one base class.
• Multilevel Inheritance: A class is derived from another derived class (a chain of inheritance).
• Hierarchical Inheritance: Multiple classes inherit from the same base class.
• Hybrid Inheritance: A combination of more than one type of inheritance, like multiple and
multilevel.
1. Single Inheritance: Child class derived directly from the base class

2. Multiple Inheritance: Child class derived from multiple base classes.


3. Multilevel Inheritance: Child class derived from the class which is also derived from another
base class.
4. Hierarchical Inheritance: Multiple child classes derived from a single base class.
5.Hybrid Inheritance: Inheritance consisting of multiple inheritance types of the above specified.
19. What is an interface?
A unique class type known as an interface contains methods but not their definitions. Inside an
interface, only method declaration is permitted. You cannot make objects using an interface. Instead,
you must put that interface into use and specify the procedures for doing so.
OR
In C++, interfaces are implemented using pure virtual functions in abstract classes. An interface is a
class that provides a blueprint for derived classes to implement specific behaior, and it has no
implementation of its own. An abstract class in C++ is a class that contains at least one pure virtual
function, and it cannot be instantiated.
20. How is an abstract class different from an interface?
Both abstract classes and interfaces are special types of classes that just include the declaration of
the methods, not their implementation. An abstract class is completely distinct from an interface,
though. Following are some major differences between an abstract class and an interface.

Abstract Class Interface

A class that is abstract can have both abstract and An interface can only have abstract
nonabstract methods. methods.

An abstract class can have final, non-final, static and The interface has only static and final
non-static variables. variables.

An interface supports multiple


Abstract class doesn’t support multiple inheritance
inheritance.

21. How much memory does a class occupy?


Classes do not use memory. They merely serve as a template from which items are made. Now,
objects actually initialize the class members and methods when they are created, using memory in
the process.
22. Is it always necessary to create objects from class?
No. If the base class includes non-static methods, an object must be constructed. But no objects
need to be generated if the class includes static methods. In this instance, you can use the class name
to directly call those static methods.
OR
No, it is not always necessary to create objects from a class in C++ (or other object-oriented
languages). There are certain situations where you can use classes without creating objects.
Here are some key examples:

1. Static Members and Static Methods


• In C++, you can define static members and static methods in a class. These belong to the
class itself rather than to any specific object of the class. As a result, you can access them
without creating an instance (object) of the class.


2. Abstract Classes
• Abstract classes, which contain at least one pure virtual function, cannot be instantiated
directly. You can only create objects from derived classes that implement the pure virtual
functions.
• By using the pure virtual function code.

23. What is the difference between a structure and a class in C++?


The structure is also a user-defined datatype in C++ similar to the class with the following differences:
• The major difference between a structure and a class is that in a structure, the members are
set to public by default while in a class, members are private by default.
• The other difference is that we use struct for declaring structure and class for declaring a
class in C++.
24. What is Constructor?
A constructor is a block of code that initializes the newly created object. A constructor resembles an
instance method but it’s not a method as it doesn’t have a return type. It generally is the method
having the same name as the class but in some languages, it might differ. For example:
In python, a constructor is named __init__.
In C++ and Java, the constructor is named the same as the class name.

• Same Name as Class: The constructor has the same name as the class. This helps the
compiler identify it as a special function that initializes objects.
• No Return Type: A constructor does not return any value. You don't even write void or any
other return type in its declaration.
• Automatically Called: When you create (instantiate) an object of a class, the constructor is
called automatically. You don’t need to call it manually.
• Used for Initialization: The main purpose of a constructor is to initialize the object’s data
(attributes) when it is created.
• Overloading is Possible: You can have more than one constructor in the same class with
different parameters (this is called constructor overloading).
• No Inheritance: Constructors are not inherited by derived classes, but the constructor of the
parent class is called when the child class object is created.
• Destructor Counterpart: A constructor has a counterpart called a destructor, which is used
to clean up or release resources when the object is destroyed.

25. What are the various types of constructors in C++?


The most common classification of constructors includes:
1. Default Constructor
2. Non-Parameterized Constructor
3. Parameterized Constructor
4. Copy Constructor
1. Default Constructor
The default constructor is a constructor that doesn’t take any arguments. It is a non-parameterized
constructor that is automatically defined by the compiler when no explicit constructor definition is
provided.
It initializes the data members to their default values.
2. Non-Parameterized Constructor
It is a user-defined constructor having no arguments or parameters.
3. Parameterized Constructor
The constructors that take some arguments are known as parameterized constructors.
4. Copy Constructor
A copy constructor is a member function that initializes an object using another object of the same
class.
In Python, we do not have built-in copy constructors like Java and C++ but we can make a
workaround using different methods.
26. What is a destructor?
A destructor is a method that is automatically called when the object is made of scope or destroyed.
In C++, the destructor name is also the same as the class name but with the (~) tilde symbol as the
prefix.
In Python, the destructor is named __del__.
In Java, the garbage collector automatically deletes the useless objects so there is no concept of
destructor in Java. We could have used finalize() method as a workaround for the java destructor but
it is also deprecated since Java 9.
27. Can we overload the constructor in a class?
Yes , We can overload the constructor in a class in Java. Constructor Overloading is done when we
want constructor with different constructor with different parameter(Number and Type).
28. Can we overload the destructor in a class?
No, a destructor cannot be overloaded in a class. There can only be one destructor present in a class.
29. What is the virtual function?
A virtual function is a function that is used to override a method of the parent class in the derived
class. It is used to provide abstraction in a class.
In C++, a virtual function is declared using the virtual keyword,
In Java, every public, non-static, and non-final method is a virtual function.
Python methods are always virtual.
30. What is pure virtual function?
A pure virtual function, also known as an abstract function is a member function that doesn’t contain
any statements. This function is defined in the derived class if needed.
A pure virtual function is a special type of virtual function that does not have an implementation in
the base class and must be overridden in any derived class. It makes the base class an abstract class,
meaning it cannot be instantiated on its own.
What is a Pure Virtual Function?
• Definition: A pure virtual function is a virtual function that is declared by appending = 0 to its
declaration.
• Abstract Class: A class containing at least one pure virtual function is called an abstract class.
Abstract classes cannot be instantiated directly but can be used as a base class for other
derived classes.
In Python, we achieve this using @abstractmethod from the ABC (Abstract Base Class) module.
Q:- what is friend function?
In Object-Oriented Programming (OOP), a friend function is a special function that is not a member
of a class but still has access to its private and protected members. This allows for a closer interaction
between functions and classes without making the function a member of the class.
Key Points About Friend Functions
1. Access to Private/Protected Members: A friend function can access private and protected
members of the class. This is useful when you need to operate on the internal state of the
class without exposing it publicly.
2. Not a Member Function: Despite having access to the class's private and protected
members, a friend function is not a member of the class. It is defined outside the class.
3. Declared Inside the Class: A class grants access to its private and protected members by
declaring a function as a friend. This declaration is made inside the class using the friend
keyword.
4. Function Signature: The friend function is declared inside the class but defined outside the
class.
5. Friend Functions and Classes: A class can have multiple friend functions, and friend
functions can be used to define relationships between classes.
Example of Friend Function
Here is a simple example demonstrating the concept of a friend function: Code
Implementation
Explanation:
1. Class Definition:
o Box is a class with private members: length, width, and height.
2. Friend Function Declaration:
o The function displayVolume() is declared as a friend of the Box class using the friend
keyword. This allows displayVolume() to access the private members of Box.
3. Function Definition:
o displayVolume() is defined outside the class but can access the private members of
Box because it is a friend.
4. Using the Friend Function:
o In the main() function, we create an instance of Box and pass it to displayVolume(),
which calculates and prints the volume of the box.
Key Points:
• Encapsulation: Friend functions break the encapsulation to some extent by accessing private
and protected data, but they are useful for certain operations where tight coupling between
the function and the class is required.
• Non-Member Function: They are not members of the class but can still access its internal
data.
• Mutual Friendships: If needed, classes can declare each other’s member functions as
friends, allowing for mutual access.
Friend functions are a powerful feature but should be used judiciously to avoid compromising the
encapsulation principles of OOP.

Bonus Question
Can we normally access the private functions?
• You cannot directly access private functions from outside the class.
• You can access them through public or protected functions within the class, allowing controlled
access to private members.
• This encapsulation helps to maintain the integrity of the data and prevents unauthorized access or
modification.
What is an abstract class?

• In general terms, an abstract class is a class that is intended to be used for inheritance. It
cannot be instantiated. An abstract class can consist of both abstract and non-abstract
methods.
• In C++, an abstract class is a class that contains at least one pure virtual function.
• In Java, an abstract class is declared with an abstract keyword.

An abstract class in C++ is a class that cannot be instantiated on its own and is used to define
a common interface for derived classes. It contains at least one pure virtual function, which
is a function declared with = 0 at the end of its declaration. Key Points:
• Abstract Class: A class with at least one pure virtual function.
• Pure Virtual Function: A function that must be overridden in derived classes. It is declared by
appending = 0 to the function declaration.
• Cannot Instantiate: You cannot create objects of an abstract class directly. Objects must be
created from derived classes that provide implementations for all pure virtual functions.

In Python, we use ABC (Abstract Base Class) module to create an abstract class.
What is deep copy and shallow copy?
• Shallow Copy: Copies the object's data but shares references to any dynamically allocated memory.
Changes in one object can affect the other.
• Deep Copy: Creates a completely independent copy of the object, including all dynamically allocated
memory. Changes in one object do not affect the other.

Simple Analogy
• Shallow Copy: Think of it as copying a list of phone numbers. If you copy the list, you have two lists
that point to the same phone numbers. If you change a phone number in one list, it changes in the
other because they both point to the same memory location.
• Deep Copy: Now imagine you take a photocopy of the entire address book, including all the phone
numbers. If you change a number in the photocopy, it does not affect the original address book
because they are completely separate copies.

• Shallow Copy:
o Shares references to nested data. o Faster and uses less memory.
o Simple to implement.
o Can lead to unintended changes due to shared references.
• Deep Copy: o Creates new copies of nested data. o Slower and
uses more memory. o More complex to implement. o Avoids
unintended changes by keeping copies independent.

Q- what is stactic keywrd?

• Static Data Members: Shared by all objects of the class. Useful for data that should be
common to all instances.
• Static Member Functions: Can be called without creating an object. Useful for utility
functions that don’t depend on instance-specific data.

You might also like