OOPS QUESTION BANK
ANSWERS
1. What is polymorphism? Explain its significance in Object-Oriented
Programming.
Answer:-
The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one
form. This is called polymorphism.
Classes and Objects : A class is like a blueprint, and an object is an instance of
that blueprint. Example: A “Car” class can create multiple “Car” objects.
Encapsulation: This principle involves bundling data (attributes) and methods
(functions) that operate on the data into a single unit called an object.
Encapsulation restricts direct access to some components, enforcing data hiding
and protecting the object’s integrity.
Abstraction: Abstraction involves hiding complex implementation details and
exposing only the necessary features of an object. This simplifies interactions and
reduces complexity by allowing users to work with high-level interfaces.
Inheritance: The capability of a class to derive properties and characteristics
from another class is called Inheritance.
Polymorphism: The word polymorphism means having many forms. In simple
words, we can define polymorphism as the ability of a message to be displayed in
more than one form. This is called polymorphism.
2. What is operator overloading? How is it implemented in C++?
Answer:-
In C++, Operator overloading is a compile-time polymorphism. It is an idea of
giving special meaning to an existing operator in C++ without changing its
original meaning.
In this article, we will further discuss about operator overloading in C++ with
examples and see which operators we can or cannot overload in C++.
C++ Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data
type, this ability is known as operator overloading. Operator overloading is a
compile-time polymorphism.
For example, we can overload an operator ‘+’ in a class like String so that we can
concatenate two strings by just using +. Other example classes where arithmetic
operators may be overloaded are Complex Numbers, Fractional Numbers, Big
integers, etc.
Key Characteristics
1. Reusing Existing Operators: It allows existing operators to work with user-
defined data types.
2. Syntax Simplification: Makes code involving custom objects more intuitive.
3. Custom Implementation: Developers define the specific behavior of operators
for their classes.
Examples:
Int a;
Float b,sum;
Sum = a + b;
Here, variables “a” and “b” are of types “int” and “float”, which are built-in
data types. Hence the addition operator ‘+’ can easily add the contents of “a”
and “b”. This is because the addition operator “+” is predefined to add variables
of built-in data type only.
// C++ Program to Demonstrate the working/Logic behind Operator
Overloading
Class A {
Statements;
};
Int main()
A a1, a2, a3;
A3 = a1 + a2;
Return 0;
}
3. Explain copy constructors with an example.
Answer:-
A copy constructor initializes a new object as a copy of an existing object.
#include <iostream>
Using namespace std;
Class Person {
Private:
String name;
Public:
Person(string n) // Parameterized constructor
Name=n;
Person(const Person &p) { // Copy constructor
Name = p.name;
Void display() {
Cout << “Name: “ << name << endl;
};
Int main() {
Person p1(“John”); // Calls parameterized constructor
Person p2 = p1; // Calls copy constructor
P2.display(); // Output: Name: John
Return 0; }
4. What is an abstract class? How does it differ from a regular class?
Answer:-
A class that contains a pure virtual function is known as an abstract class.
Feature Abstract Class Regular Class
Instantiation Cannot be instantiated directly Can be instantiated normally
Methods Can have both abstract (without All methods have
implementation) and concrete implementations
(with implementation) methods
Purpose Serves as a blueprint for Can be used as a standalone class
subclasses
Usage Enforces structure and contract Used for creating actual objects
for subclasses
5. What are the advantages of inheritance in C++?
Answer:-
Code Reusability: Inheritance allows the reuse of existing code, reducing
redundancy.
Extensibility: New features can be added to existing classes without modifying
them.
Maintenance: Updates made in the base class are automatically reflected in
derived classes.
Abstraction: Helps in representing real-world relationships (like is-a).
Polymorphism: Facilitates method overriding, allowing derived classes to
implement base class methods Differently.
6. How does multilevel inheritance work? Provide an example.
Answer:-
A chain of inheritance where a derived class acts as a base class for another.
Example:
Class A {
// Members
};
Class B : public A {
// Members
};
Class C : public B {
// Members
};
Advantages:
Clear representation of hierarchies.
Code reuse across multiple levels.
7. What is a constructor? Explain its role in object initialization.
Answer:
A constructor is invoked when an object of a class is Created. Its primary
purpose is to initialize the object’s attributes. Constructors can be default (no
parameters), parameterized (with Parameters), or copy constructors (to create a
copy of an object).
Role in Object Initialization:
1. Automatic Execution: The constructor is invoked automatically when an
object is instantiated.
2. Initializes Object Attributes: It sets up the initial state of an object by
assigning values to its attributes.
3. Encapsulation of Initialization Logic: Instead of setting attributes manually
after creating an object, the constructor ensures the object is in a valid state
from the start.
4. Code Reusability: A constructor allows common initialization code to be
written once and reused every time an object is created.
8. What are file operations in C++? Explain different file-handling modes.
Answer:-
File operations in C++ refer to the various ways in which a program can interact
with files, such as reading, writing, and manipulating file contents.
9. Explain function overloading with an example.
Answer:-
Function overloading is a programming concept where multiple functions can
share the same name but differ in their parameter lists. This allows a single
function name to perform different tasks based on the arguments provided.
Function overloading is a form of polymorphism (specifically, compile-time
polymorphism) commonly supported in languages like C++, Java, and Python
(indirectly).
Key Characteristics:
1. Same Function Name: Multiple functions share the same name.
2. Different Parameter Signatures: Functions must differ in the:
● Number of parameters.
● Types of parameters.
● Order of parameters.
3. Compile-Time Decision: The appropriate function is determined at compile
time based on the arguments provided in the function call.
Examples:
#include <iostream>
Using namespace std;
Class Example {
Public:
Void display(int a) {
Cout << “Integer: “ << a << endl;
Void display(double b) {
Cout << “Double: “ << b << endl;
Void display(string c) {
Cout << “String: “ << c << endl;
};
Int main() {
Example ex;
Ex.display(10); // Calls the version with an integer parameter
Ex.display(3.14); // Calls the version with a double parameter
Ex.display(“Hello”); // Calls the version with a string parameter
Return 0;}
Advantages:
● Improves code readability and organization.
● Reduces the need for distinct function names for similar operations.
● Allows flexibility in handling various data types or parameter sets.
Limitations:
● Overuse can make code harder to debug.
● Not directly supported in all languages (e.g., Python needs workarounds).
● Ambiguity may arise if overloading rules aren’t clearly defined.
10. What are member functions? How are they defined inside and outside a class?
Answer:
A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable. It operates on any object of the
class of which it is a member, and has access to all the members of a class for
that object.
• Defining Member Function inside the Class
Class Box
Public:
Double length; // Length of a box
Double breadth; // Breadth of a box
Double height; // Height of a box
Double getVolume(void)
Return length * breadth * height;
};
• Defining Member Function outside of the Class
If you like, you can define the same function outside the class using the scope
resolution operator (:: as Follows –
Double Box::getVolume(void)
Return length * breadth * height;
Here, only important point is that you would have to use class name just before
“::” operator.
11. What is the difference between throw and catch? Explain with an example.
Answer:-
When executing C++ code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message.
The technical term for this is: C++ will throw an exception (throw an error).
C++ try and catch
Exception handling in C++ consist of three keywords: try, throw and catch:
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
The throw keyword throws an exception when a problem is detected, which lets
us create a custom error.
The catch statement allows you to define a block of code to be executed, if an
error occurs in the try block.
12. What is a virtual function? Why is it needed in C++?
Answer:-
A virtual function (also known as virtual methods) is a member function that is
declared within a base class and is re-defined (overridden) by a derived class.
When you refer to a derived class object using a pointer or a reference to the
base class, you can call a virtual function for that object and execute the derived
class’s version of the method.
● Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for the function call.
● They are mainly used to achieve Runtime polymorphism.
● Functions are declared with a virtual keyword in a base class.
● The resolving of a function call is done at runtime.
Rules for Virtual Functions
The rules for the virtual functions in C++ are as follows:
1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using a pointer or reference of base class
type to achieve Runtime polymorphism.
4. The prototype of virtual functions should be the same in the base as well as
the derived class.
5. They are always defined in the base class and overridden in a derived class. It
is not mandatory For the derived class to override (or re-define the virtual
function), in that case, the base class Version of the function is used.
6. A class may have a virtual destructor but it cannot have a virtual
constructor.
Compile time (early binding) VS runtime (late binding) behavior of Virtual
Functions
Consider the following simple program showing the runtime behavior of virtual
functions.
// C++ program to illustrate concept of Virtual Functions
#include <iostream>
Class base {
Public:
Virtual void print() { cout << “print base class\n”; }
Void show() { cout << “show base class\n”; }
};
Class derived : public base {
Public:
Void print() { cout << “print derived class\n”; }
Void show() { cout << “show derived class\n”; }
};
Int main()
Base* bptr;
Derived d;
Bptr = &d;
// Virtual function, binded at runtime
Bptr->print();
// Non-virtual function, binded at compile time
Bptr->show();
Return 0;
Output:
Print derived class
Show base class
13. Explain the concept of pure virtual functions with an example.
Answer:-
Pure virtual functions are used
● if a function doesn’t have any use in the base class
● but the function must be implemented by all its derived classes
Let’s take an example,
Suppose, we have derived Triangle, Square and Circle classes from the Shape
class, and we want to calculate the area of all these shapes.
In this case, we can create a pure virtual function named calculateArea() in the
Shape. Since it’s a pure
Virtual function, all derived classes Triangle, Square and Circle must include the
calculateArea() function with implementation.
A pure virtual function doesn’t have the function body and it must end with = 0.
For example,
Class Shape {
Public:
// creating a pure virtual function
Virtual void calculateArea() = 0;
};
14. What is exception handling? Why is it important in programming?
Answer:- NOTE:- REFER Q.11 SAME ANSWER
15. How are files opened and closed in C++? Provide an example.
Answer:-
How to open a file?
By using the object of any file stream class, we could call the open() function,
using which we could provide location of the file stored on the disk and in
return(if the file is found), the open() function opens the file in a specific mode to
let you perform a specific file operation.
Let us take a look at a general syntax of open() function to open a file.
file-stream-object("filename", mode); file-stream-object, is the an of a file
stream class used to perform a specific file operation.
filename, is the name of a file on which we are going to perform file operations.
mode, is single or multiple file modes in which we are going to open a file.
16. Describe the key principles of Object-Oriented Programming (OOP).
Answer:-
Classes and Objects : A class is like a blueprint, and an object is an instance of
that blueprint. Example: A “Car” class can create multiple “Car” objects.
Encapsulation: This principle involves bundling data (attributes) and methods
(functions) that operate on the data into a single unit called an object.
Encapsulation restricts direct access to some components, enforcing data hiding
and protecting the object’s integrity.
Abstraction: Abstraction involves hiding complex implementation details and
exposing only the necessary features of an object. This simplifies interactions and
reduces complexity by allowing users to work with high-level interfaces.
Inheritance: The capability of a class to derive properties and characteristics
from another class is called Inheritance.
Polymorphism: The word polymorphism means having many forms. In simple
words, we can define polymorphism as the ability of a message to be displayed in
more than one form. This is called polymorphism.
17. Explain file streams and their types in C++.
Answer:-
The fstream library allows us to work with files.
To use the fstream library, include both the standard <iostream> AND the
<fstream> header file:
Example
#include <iostream>
#include <fstream>
There are three classes included in the fstream library, which are used to create,
write or read files:
18. Explain the exception handling mechanism in C++.
Answer:- NOTE:- REFER Q.11 SAME ANSWER
19. What are friend functions? How do they access private members of a class?
Answer:-
If a function is defined as a friend function in C++, then the protected and
private data of a class can be accessed using the function.
By using the keyword friend compiler knows the given function is a friend
function.
For accessing the data, the declaration of a friend function should be done inside
the body of a class starting with the keyword friend.
Declaration of friend function in C++
Class class_name
Friend data_type function_name(argument/s); // syntax of friend function.
};
Me(argument/s); // syntax of friend function.
};
In the above declaration, the friend function is preceded by the keyword friend.
The function can be Defined anywhere in the program like a normal C++
function. The function definition does not use either The keyword friend or scope
resolution operator.
Characteristics of a Friend function:
● The function is not in the scope of the class to which it has been declared as a
friend.
● It cannot be called using the object as it is not in the scope of that class.
● It can be invoked like a normal function without using the object.
● It can be declared either in the private or the public part.
C++ Friend class
A friend class can access both private and protected members of the class in
which it has been declared as Friend.
Example:
#include <iostream>
Class A
Int x =5;
Friend class B; // friend class.
};
Class B
Public:
Void display(A &a)
Cout<<”value of x is : “<<a.x;
};
Int main()
A a;
B b;
b.display(a);
return 0;
Output:
Value of x is : 5
In the above example, class B is declared as a friend inside the class A.
Therefore, B is a friend of class A. Class B can access the private members of
class A.
20. What is inheritance? How does it promote code reusability?
Answer:-
The capability of a class to derive properties and characteristics from another
class is called Inheritance.
1. Code Duplication Reduced: Inheritance allows you to define a common set of
attributes and methods in a superclass, which can be shared by multiple
subclasses.
2. Modularity: Inheritance enables you to break down a complex system into
smaller, more manageable modules, each representing a specific class or
subclass.
3. Easier Maintenance: When a change Is required, you only need to modify the
superclass, and the changes will be automatically reflected in all the
subclasses.
4. Faster Development: Inheritance Allows you to create new classes quickly by
building upon existing classes, reducing the overall development time.
21. What is multiple inheritance? Explain with an example.
Answer:-
A derived class inherits from multiple base classes.
Syntax:
Class Derived : public Base1, public Base2 {
// Members
};
Advantages:
Combines features of multiple base classes.
Challenges:
Ambiguity (e.g., Diamond problem).
Increased complexity.
22. Define polymorphism. Explain its types with examples.
Answer:-
The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one
form. This is called polymorphism.
1. Compile-Time :-
This type of polymorphism is achieved by function overloading or operator
overloading.
• Function Overloading :-
When there are multiple functions with the same name but different
parameters, then the functions are said to be overloaded, hence this is known
as Function Overloading.
• Operator Overloading :-
C++ has the ability to provide the operators with a special meaning for a data
type, this ability is known as operator overloading.
2. Runtime Polymorphism :-
This type of polymorphism is achieved by Function Overriding. Late binding
and dynamic polymorphism are other names for runtime polymorphism. The
function call is resolved at runtime in runtime polymorphism.
• Virtual Function:-
A virtual function is a member function that is declared in the base class
using the keyword virtual and is re-defined (Overridden) in the derived class.
23. Explain how a class is defined in C++ and how its members are accessed.
Answer:-
A class is defined in C++ using the keyword class followed by the name of the
class. The following is the
Syntax:
Class ClassName
{
Access_specifier:
// Body of the class
};
Here, the access specifier defines the level of access to the class’s data members.
Example
Class ThisClass
Public:
Int var; // data member
Void print()
{ // member method
Int a;
Cout << “Hello”;
Printf(“a”)
};
24. What is a constructor and destructor? Explain with an example.
Answer:-
• Constructor :- A constructor is invoked when an object of a class is Created.
Its primary purpose is to initialize the object’s attributes. Constructors can
be default (no parameters), parameterized (with Parameters), or copy
constructors (to create a copy of an object).
• Destructor:- A destructor is invoked when an object is destroyed. Its primary
purpose is to free resources that the object may have acquired during its
lifetime, such as dynamic memory, file handles, or network connections.
Example :
#include <iostream>
Using namespace std;
Class MyClass {
Public:
// Constructor
MyClass() {
Cout << “Constructor called! Object is created.” << endl;
// Destructor
~MyClass() {
Cout << “Destructor called! Object is destroyed.” << endl;
Void display() {
Cout << “Hello from MyClass!” << endl;
};
Int main() {
// Creating an object of MyClass
MyClass obj;
// Calling a member function
Obj.display();
// The destructor will be called automatically when the object goes out of scope
Return 0;
GOD’S PLAN BABY !!!
There is a 1% chance, and sometimes that chance is good enough.