OOP Sample Question Bank Solution
OOP Sample Question Bank Solution
OOP Sample Question Bank Solution
Classes
Classes contain a group of objects that share common properties for data parts. A class is a
blueprint for an object where all the attributes, methods, and other aspects are.
A class helps in data binding and making the code reusable. For example, a Dog has attributes
like species, color, etc., but the attributes of the class Dog are the same for the different breeds
and colors.
Objects
An object is an entity with some properties and behaviours. When an object is instantiated at
that time, the memory is allocated. Each object has the ability to interact without having to
know details of each other's information or code.
For example, Dog is the object of the breed’s name Pomeranian, having its properties and
behaviours.
class Dog
{
char name[20];
char color[10];
public:
void details(){}
};
int main()
{
Dog obj; // obj is a object
}
Encapsulation
Encapsulation in oops means to enclose all the important information in a capsule and expose
all the other selected information to the outside world. It is important to encapsulate the data
from attackers from modifying the data in the database.
For example, if you want your money from the ATM machine, the machine processes your
request and gives you the money. It contains both data and functions wrapped under a single
machine.
Encapsulation helps in binding data and methods. It also leads to abstraction or data hiding. In
the above example, the internal working of the machine is hidden.
Abstraction
Abstraction is what a developer needs to implement in the software or a product for a better
user experience.
Basically, abstraction is to hide all the complexities and displays only essential information to
the outside world.
Let's consider an example of making coffee with a coffee machine. For this, you need to know
how to use your coffee machine. Just provide the essential ingredients, switch it on and select
the type of coffee you want. Now you need to know the internal working of the coffee
machine.
Super Class: The class from which the properties are inherited by the sub class/child class.
Sub Class: The class which inherits the properties from the super class/parent class.
Inheritance helps you do the separation of the same fields and functionality so that it can be
reused in other classes. And this helps in code redundancy.
Composition:Composition is the procedure of combining two or more objects together to
create a new and unique object. Through this process developers find it easy to reuse the
elements specifically needed for the object to create a new and unique object.
Polymorphism
Polymorphism means to have the same name of a method performing different tasks. For
example, in finding out the area of the shape, the area of the square is length2, and the area of
the rectangle is length*breadth.
It has the ability to display the message in more than one form. A person can possess different
characteristics at the same time, so this is what polymorphism is all about.
Output:
Explanation:
Both Person and Child classes have the same method, i.e., walks(), and the Child class overrides
the walks() method by having its own implementation.
Static Polymorphism/ Method Overloading: It occurs when methods with the same name have
differences in the number and types of parameters.
For example:
class Example {
private static void show(int x){
System.out.println(x);
}
Explanation:
In the above code, the show() method is overloaded by changing the number of parameters as
well as by changing the name of the data type. So this is known as Method Overloading.
Polymorphism has the ability to perform different tasks with the same method, due to which
the code is clean.
Data Binding
Binding means to bind one thing to another one. Here in OOPS, binding refers to linking some
attribute of one object to another one in the Application.
There are two main types of binding:
• Static Binding
• Dynamic binding
}
private void play(){
System.out.println("person is playing.");
}
public static void main(String args[]){
Person obj=new Person();
obj.walks();
obj.play();
}
}
Output:
Explanation
When any type of object is determined at the compile time, then it is known as static binding.
Also, play() and walks() are private methods, and that is the reason for the static binding.
Dynamic Binding:
When any object is determined at the run time, then it is known as dynamic binding.
Dynamic Binding occurs when the property of one object changes, and due to this, the property
of another object gets changed.
class Person{
void walks(){
System.out.println("Person is walking.");
}
}
Output:
Explanation
In the above code, the instance of Child is also an instance of Person, So the compiler can't
determine the object type.
Message Passing
Passing data around the program is the most important feature of the oop concept. Message
passing is the sending of a message from one object to another. How does this occur?
As we know that each object has its own specific address that other objects can use to send
messages. Now that object can do whatever it needs to do based on the message. Multiple
objects can communicate with each other in interesting ways.
3. Explain benefits of OOP.
• There are miscellaneous benefits of oops we have to just focus on learning. It is a vast concept
by which we can make good decisions as a developer (explain any two benefits of oops)
• We can develop the programs from standard working modules that communicate with one
another, rather than having to start writing the code from abrasion which leads to saving of
development time and advanced productivity.
• The benefits of OOPs language allow it to break the program into bit-sized problems that can
be answered fluently (one object at a time).
• The new technology promises higher programmer productivity, a better quality of software,
and lower conservation cost.
• The benefits of OOPs systems can be fluently upgraded from small to large systems.
• It’s possible that multiple cases of objects co-occur without any embarrassment.
• It’s actually easy to partition the work into a design grounded on objects.
• It’s possible to frame the objects in the problem area to those in the program.
• Data hiding’s principle is to help the programmer to make secure programs that can not be
raided by the code in other corridors of the program.
• By using legacy, we can exclude extra programmes and extend the use of being classes.
• Communication passing methods are used for communication between objects which makes
the interface descriptions with external systems much simpler.
• The data-centered design approach enables us to capture further details of the model in an
implementable form.
1. In parallel programming, an issue is split up into smaller subproblems that can all be
worked on simultaneously utilizing different computing resources. OOPs, are utilized to
streamline the procedure by improving the network’s capacity for approximation and
prediction.
2. When creating client-server systems, OOPs principles are quite helpful. To construct
Object-oriented server internet, or OCSI, applications, the IT infrastructure is created using
Object-oriented client-server systems.
3. OOP can be used to reduce the amount of work required in manufacturing and designing
applications. It can be applied, for instance, when creating flowcharts and blueprints. So, it
makes it possible to produce these flowcharts and blueprints accurately.
4. OOP is helpful in hypertext and hypermedia. It aids in laying the framework for hypertext
and hypermedia
5. Simulation and modelling systems are imitations of the real-world product. The system’s
workings can be checked and analysed using object-oriented programming.
6. OOP helps users to minimize the work required and can be applied in both application
design and manufacturing. For example, it can be applied when creating flowcharts and
blueprints. The ability to precisely construct these flowcharts and blueprints is therefore
made possible.
7. OOP is beneficial in hypermedia and hypertext. It assists in establishing the foundation for
hypertext and hypermedia.
8. Systems used for simulation and modelling are an emulation of real-world products. Using
object-oriented programming, the operation of the system may be examined.
9. The conventional form of storing data, known as the relational model, saves every single
piece of data in tables made up of rows and columns. Today, every single piece of data is
stored and processed in object-oriented databases.
10. It is beneficial in computer-aided design (CAD), which uses workstations or computers to
assist in the creation, modification, analysis, or optimization of a design.
Definition This programming language makes use of a This programming language uses objects and
step-by-step approach for breaking down a classes for creating models based on the real-
task into a collection of routines (or world environment. This model makes it very
subroutines) and variables by following a easy for a user to modify as well as maintain
sequence of instructions. It carries out each the existing code while new objects get
step systematically in order so that a computer created by inheriting the characteristics of the
easily gets to understand what to do. present ones.
Security Procedural Programming does not offer any Hiding data is possible with Object Oriented
method of hiding data. Thus, it is less secure Programming due to the abstraction. Thus, it is
when compared to Object Oriented more secure than the Procedural
Programming. Programming.
Method The main program gets divided into minute It involves the concept of classes and objects.
parts based on the functions. It then treats Hence, it divides the program into minute
them as separate programs for smaller chunks known as objects. These are instances
programs individually. of classes.
Division of Procedural Programming divides the program Object Oriented Programming divides the
Program into small programs and refers to them as program into small parts and refers to them as
functions. objects.
Movement of Available data can move freely within the The objects can move and communicating
Data system from one function to another. with each other through the member
functions.
Approach The Procedural Programming follows a Top- The Object-Oriented Programming follows a
Down approach. Bottom-Up approach.
Importance This programming model does not give This programming model gives importance to
importance to data. It prioritizes the functions the data rather than functions or procedures.
along with the sequence of actions that needs It is because it works based on the real world.
to follow.
Basis The main focus in Procedural Programming is The main focus in Object Oriented
on how to do the task, meaning, on the Programming is on data security. Hence, it
structure or procedure of the program. only permits objects to access the class
entities.
Inheritance It does not provide any inheritance. It achieves inheritance in three modes-
protected, private, and public.
Virtual Classes There is no concept of virtual classes. The concept of virtual functions appears at the
time of inheritance.
Overloading The case of overloading is not possible in the Overloading is possible in the form of operator
case of Procedural Programming. overloading and function overloading in the
case of Object-Oriented Programming.
Reusability of No feature of reusing codes is present in Object Oriented Programming offers the
Code Procedural Programming. feature to reuse any existing codes in it by
utilizing a feature known as inheritance.
Modes of The Procedural Programming offers no specific The Object Oriented Programming offers three
Access accessing mode for accessing functions or accessing modes- protected, private, and
attributes in a program. public. These, then, serve as a share to access
functions of attributes.
Size of It is not very suitable for solving any big or It is suitable for solving any big or complex
Problems complex problems. problems.
Addition of It is not very easy to add new functions and It is very easy to add new functions and data in
New Function data in the Procedural Programming. the Object Oriented Programming.
and Data
Access to Data In the Procedural Programming, most of the In the Object Oriented Programming, the
functions use global data for sharing. They can present data cannot easily move easily from
access freely from one function to another in one function to another. One can keep it
any given system. private or even public. Thus, a user can control
the data access.
Data Sharing It shares the global data among the functions It shares data among the objects through its
present in the program. member functions.
Data Hiding No proper way is available for hiding the data. It can hide data in three modes- protected,
Thus, the data remains insecure. private, and public. It increases the overall
data security.
Basis of World The Procedural Programming follows an unreal The Object Oriented programming follows the
world. real world.
Friend Classes It does not involve any concept of friend Any class or function is capable of becoming a
or Friend function. friend of any other class that contains the
Functions keyword “friend.”
struct stud_id
{
char name[20];
int class;
int roll_number;
char address[30];
};
This is called the declaration of the structure, and it is terminated by a semicolon (;). The memory is not
allocated, while the structure declaration is delegated when specifying the same. The structure
definition creates structure variables and allocates storage space for them. One can define the
Where I1 and I2 are the two variables of stud_id. After defining the structure, one can access its
members using the dot operator as follows: I1.roll_number will access the roll number of I1
struct stud_id
};
int main ()
entries[0].roll_number = 20;
return 0;}
9. Explain memory allocation for objects.
In object-oriented programming (OOP) with C++, memory allocation for objects is typically handled
through the following mechanisms:
When you declare an object as a local variable inside a function or a block, memory for that object is
automatically allocated on the stack. This is the default behavior in C++. The memory is automatically
deallocated when the object goes out of scope.
void someFunction() {
// ...
In this example, the memory for the object `obj` of class `MyClass` is allocated on the stack when
`someFunction` is called. The memory is automatically released when the function returns.
If you need to allocate memory for objects dynamically at runtime or if you want the object's lifetime
to extend beyond its scope, you can use dynamic memory allocation on the heap. This is done using the
`new` operator to allocate memory and the `delete` operator to deallocate it.
// ...
In this example, the `new` operator dynamically allocates memory for an object of class `MyClass` on
the heap. The `delete` operator is used to deallocate the memory and invoke the destructor explicitly.
When using dynamic memory allocation, it's important to manage the memory correctly to avoid
memory leaks. Remember to use `delete` to deallocate the memory when you're done with the object.
Failure to do so can result in memory leaks and inefficient memory usage.
Additionally, C++ provides the `new[]` and `delete[]` operators for dynamic memory allocation of
arrays of objects on the heap. These operators allocate and deallocate memory for object arrays, and
they require special handling when it comes to deallocation to ensure the correct deallocation of each
element in the array.
MyClass* objArray = new MyClass[10]; // Allocate an array of 10 MyClass objects on the heap
// ...
Here, the `new[]` operator is used to allocate an array of 10 `MyClass` objects on the heap, and
`delete[]` is used to deallocate the memory for the array.
It is important to be cautious with dynamic memory allocation and deallocation to prevent memory
leaks, dangling pointers, or accessing deallocated memory. Consider using smart pointers or standard
library containers like `std::vector` or `std::unique_ptr` to automate memory management and reduce
the chances of memory-related errors.
In object-oriented programming, member functions (also known as methods) are functions defined
within a class that operate on the class's objects. They encapsulate behavior and actions that can be
performed on the data members of the class. Here's an explanation of how member functions of a
class are defined in a program:
Syntax:
The syntax for defining a member function within a class typically looks like this:
• ClassName is the name of the class.
• returnType specifies the type of value returned by the member function. If the function doesn't
return a value, the return type is void.
• functionName is the name of the member function.
• parameterList is a comma-separated list of input parameters (if any) that the member function
accepts.
Access Specifiers:
Member functions can have different access specifiers, such as public, private, or protected, which
control the visibility and accessibility of the function.
• public member functions can be accessed from anywhere, both within the class and from
external code.
• private member functions are only accessible within the class itself and cannot be accessed
directly from external code.
• protected member functions are accessible within the class and its derived classes.
Member functions can be defined inside the class declaration itself or outside the class using the
scope resolution operator :: to specify the class to which the function belongs.The function body
contains the implementation of the member function, where you can write the code to perform the
desired operations. You can access the class's data members and call other member functions within
the function body.
Function Body:
The function body contains the implementation of the member function, where you can write the
code to perform the desired operations. You can access the class's data members and call other
member functions within the function body.
To call a member function, you need to create an object of the class and use the object to invoke the
member function using the dot (.) operator.
If the member function is static, you can call it directly using the class name without creating an
object.
That's a basic overview of how member functions are defined in a program. Remember that the
specific syntax and rules may vary depending on the programming language you are using, so it is
important to refer to the documentation or language-specific guidelines for detailed information.
12. Write C++ program with class for displaying student information.
#include <iostream>
#include <string>
class Student {
private:
std::string name;
int age;
std::string rollNumber;
public:
// Constructor
Student(std::string n, int a, std::string roll) {
name = n;
age = a;
rollNumber = roll;
}
// Member function to display student information
void displayInfo() {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "Roll Number: " << rollNumber << std::endl;
}
};
int main() {
// Create an object of the Student class
Student student1("John Doe", 20, "A001");
// Call the displayInfo() member function to display student information
student1.displayInfo();
return 0;
}
• A constructor is a special type of member function that is called automatically when an object is
created.In C++, a constructor has the same name as that of the class and it does not have a
class Wall {
public:
// create a constructor
Wall() {
// code
}
};
Here, the function Wall() is a constructor of the class Wall. Notice that the constructor
• is public
This is useful, when we want to initialize all data members of an object with another object, we
can pass objects and assign the values of supplied object to the current object. For complex or
large projects, we need to use objects as an argument or parameter.
#include <iostream>
using namespace std;
class Demo {
private:
int a;
public:
void set(int x)
{
a = x;
}
void print()
{
cout << "Value of A : " << a << endl;
}
};
int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;
return 0;
}
Output
Value of A : 10
Value of A : 20
Value of A : 30
Above example demonstrate the use of object as a parameter. We are passing d1 and d2 objects as
arguments to the sum member function and adding the value of data members a of both objects
and assigning to the current object’s (that will call the function, which is d3) data member a.
17. Explain how we can pass and return the object as function argument.
> In C++ programming, we can pass objects to a function in a similar manner as passing regular
arguments.
#include <iostream>
using namespace std;
class Student {
public:
double marks;
int main() {
Student student1(88.0), student2(56.0);
return 0;
}
Run Code
Output
Average Marks = 72
Here, we have passed two Student objects student1 and student2 as arguments to
#include <iostream>
using namespace std;
class Student {
public:
double marks1, marks2;
};
return student;
}
int main() {
Student student1;
// Call function
student1 = createStudent();
return 0;
}
Run Code
Output
Marks1 = 96.5
Marks2 = 75
In this program, we have created a function createStudent() that returns an object of Student class.
// Call function
student1 = createStudent();
Here, we are storing the object returned by the createStudent() method in the student1.
-> There are 3 types of Constructors in C++. Let’s learn about them.
1. Default Constructor
A constructor with no arguments (or parameters) in the definition is a default constructor. It is the type
of constructor in C++ usually used to initialize data members (variables) with real values.
Note: The compiler automatically creates a default constructor without data member (variables) or
initialization if no constructor is explicitly declared.
class CLASS_NAME
………
public :
CLASS_NAME() //Default constructor
......
};
Example:
#include <iostream>
class Default_construct
public:
int a, b;
// Default Constructor
Default_construct()
a = 100;
b = 200;
};
int main()
{
return 0;
2. Parameterized Constructor
Unlike the Default constructor, It contains parameters (or arguments) in the constructor definition and
declaration. More than one argument can also pass through a parameterized constructor.
Moreover, this type of constructor in C++ is used for overloading to differentiate between multiple
constructors.
Syntax –
class class_Name
public:
………………..
};
Example:
#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double breadth;
public:
// parameterized constructor
Rectangle(double l, double b) {
length = l;
breadth = b;
double calculateArea() {
};
int main() {
Rectangle obj1(10,6);
Rectangle obj2(13,8);
}
3. Copy Constructor
A copy constructor is the third type among various types of constructors in C++. The member function
initializes an object using another object of the same class. It helps to copy data from one object to
another.
Example –
#include <iostream>
class Rectangle {
private:
double length;
double breadth;
public:
// parameterized constructor
Rectangle(double l, double b) {
length = l;
breadth = b;
// copy constructor with a Rectangle object as parameter copies data of the obj
parameter
Rectangle(Rectangle &obj) {
length = obj.length;
breadth = obj.breadth;
double calculateArea() {
};
int main() {
Rectangle obj1(10,6);
return 0;
struct X {
static int f();
};
int main() {
X::f();
}
• The Array object lets you store multiple values in a single variable. It stores a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables of the same type.
Syntax
Use the following syntax to create an Array object −
var fruits = new Array( "apple", "orange", "mango" );
The Array parameter is a list of strings or integers. When you specify a single numeric parameter with
the Array constructor, you specify the initial length of the array. The maximum length allowed for an
array is 4,294,967,295.
You can create array by simply assigning values as follows −
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
#include <iostream>
cout<<greet<<endl;
Output:
As you can see in the above output, it eliminates the need for declaring an array to hold characters.
23. List the operators which can be overloaded and which cannot.
24. Explain unary operator overloading with example.
The unary operators operate on a single operand and following are the examples of Unary operators −
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
int main() {
Distance D1(11, 10), D2(-5, 11);
return 0;
}
When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11
Hope above example makes your concept clear and you can apply similar concept to overload Logical
Not Operators (!).
25. Explain binary operator overloading with example.
An operator which contains two operands to perform a mathematical operation is called the Binary
Operator Overloading. It is a polymorphic compile technique where a single operator can perform
various functionalities by taking two operands from the programmer or user. There are multiple binary
operators like +, -, *, /, etc., that can directly manipulate or overload the object of a class.
For example, suppose we have two numbers, 5 and 6; and overload the binary (+) operator. So, the
binary (+) operator adds the numbers 5 and 6 and returns 11. Furthermore, we can also perform
subtraction, multiplication, and division operation to use the binary operator for various calculations.
Here,
binary_operator_symbol: It represents the binary operator symbol that overloads a function to perform
the calculation.
There are various relational operators supported by C++ language like (<, >, <=, >=, ==, etc.) which can
be used to compare C++ built-in data types.
You can overload any of these operators, which can be used to compare the objects of a class.
Following example explains how a < operator can be overloaded and similar way you can overload other
relational operators.
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
// method to display distance
void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}
return false;
}
};
int main() {
Distance D1(11, 10), D2(5, 11);
if( D1 < D2 ) {
cout << "D1 is less than D2 " << endl;
} else {
cout << "D2 is less than D1 " << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
D2 is less than D1
There are different kinds of the operators, such as arithmetic, relational, bitwise,
assignment, etc., in the C programming language. The assignment operator is used to
assign the value, variable and function to another variable. Let's discuss the various
types of the assignment operators such as =, +=, -=, /=, *= and %=.
Example of the Assignment Operators:
It is the operator used to assign the right side operand or variable to the left side
variable.
Syntax
1. int a = 5;
2. or int b = a;
3. ch = 'a';
Program1.c
1. #include <stdio.h>
2. #include <conio.h>
3. int main ()
4. {
5. // initialize variables
6. int n1, n2, c, x, y;
7. n1 = 5;
8. n2 = n1;
9. c = n1 + n2;
10. x = 20 / 4 * 2 + 5;
11. printf (" \n The value of n1: %d", n1);
12. printf (" \n The value of n2: %d", n2);
13. printf (" \n The value of c: %d", c);
14. printf (" \n The value of x: %d", x);
15. return 0;
16. }
Output
• An array of pointers is an array that consists of variables of pointer type, which means
that the variable is a pointer addressing to some other element. Suppose we create an
array of pointer holding 5 integer pointers; then its declaration would look like:
A pointer is a variable that stores the memory address of another variable (or object) as its value. A
pointer aims to point to a data type which may be int, character, double, etc. Pointers to objects aim to
make a pointer that can access the object, not the variables. Pointer to object in C++ refers to accessing
an object. There are two approaches by which you can access an object. One is directly and the other is
by using a pointer to an object in c++.
• A pointer to an object in C++ is used to store the address of an object. For creating a pointer to
an object in C++, we use the following syntax:
classname*pointertoobject;
For storing the address of an object into a pointer in c++, we use the following syntax:
pointertoobject=&objectname;
The above syntax can be used to store the address in the pointer to the object. After storing the address
in the pointer to the object, the member function can be called using the pointer to the object with the
help of an arrow operator.
32. Explain inheritance with an example.
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
class Animal {
// eat() function
// sleep() function
};
Here, the Dog class is derived from the Animal class. Since Dog is derived from Animal,
Inheritance in C++
Notice the use of the keyword public while inheriting Dog from Animal.
We can also use the keywords private and protected instead of public. We will learn about
the differences between using private, public and protected later in this tutorial.
ANS- A class that is created from an existing class. The derived class inherits all members and member functions
of a base class. The derived class can have more functionality with respect to the Base class and can easily access
the Base class. A Derived class is also called a child class or subclass.
Syntax for creating Derive Class:
class BaseClass{
// members....
// member function
// members....
// member function
}
34. Explain constructors in derived classes with suitable example.
35. Explain function overloading with example.
ANS- unction overloading is a C++ programming feature that allows us to have more than one function having
same name but different parameter list, when I say parameter list, it means the data type and sequence of the
parameters, for example the parameters list of a function myfuncn(int a, float b) is (int,
float) which is different from the function myfuncn(float a, int b) parameter list (float,
int). Function overloading is a compile-time polymorphism.
#include <iostream>
using namespace std;
class Addition {
public:
int sum(int num1,int num2) {
return num1+num2;
}
int sum(int num1,int num2, int num3) {
return num1+num2+num3;
}
};
int main(void) {
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
return 0;
}
Output:
35
191
36. Write a program in C++ to overload a function AREA() to calculate the area of a triangle, square,
and rectangle.
#include<iostream>
int area(int);
int area(int,int);
float area(float);
float area(float,float);
int main()
int s,l,b;
float r,bs,ht;
cin>>s;
cin>>l>>b;
cin>>r;
cin>>bs>>ht;
}
int area(int s)
return(s*s);
return(l*b);
float area(float r)
return(3.14*r*r);
return((bs*ht)/2);
OUTPUT : :
Area of rectangle is 18
In inheritance, the accessibility of members (properties and methods) within derived classes depends
on the access specifiers used in the base class. There are three main access specifiers used in
inheritance: public, private, and protected. Let's explore how these access specifiers affect member
accessibility:
Public Inheritance:
• Public members: Public members of the base class remain public in the derived class. They can
be accessed directly from the derived class and also from outside the derived class.
• Protected members: Protected members of the base class become protected members in the
derived class. They are accessible within the derived class and its derived classes but cannot be
accessed from outside the hierarchy.
• Private members: Private members of the base class are not accessible in the derived class.
Protected Inheritance:
• Public members: Public members of the base class become protected members in the
derived class. They can be accessed within the derived class and its derived classes but not
from outside the hierarchy.
• Protected members: Protected members of the base class become protected members in the
derived class. They are accessible within the derived class and its derived classes but cannot
be accessed from outside the hierarchy.
• Private members: Private members of the base class are not accessible in the derived class.
Private Inheritance:
• Public members: Public members of the base class become private members in the derived
class. They are accessible within the derived class but not from outside the derived class or
its derived classes.
• Protected members: Protected members of the base class become private members in the
derived class. They are accessible within the derived class but not from outside the derived
class or its derived classes.
• Private members: Private members of the base class are not accessible in the derived class.
It's important to note that the accessibility of base class members within the derived class is
determined by the access specifier used when inheriting. For example, if a derived class inherits using
the public keyword (class Derived : public Base), the public and protected members of the base class
retain their accessibility in the derived class. If a derived class inherits using the private keyword
(class Derived : private Base), both the public and protected members become private in the derived
class.
It's also worth mentioning that when using access specifiers, the accessibility of members in the base
class itself remains unchanged. The access specifiers primarily affect the derived classes and their
relationship with the base class.
By understanding the accessibility rules in inheritance, you can control the visibility and accessibility
of members in a class hierarchy, ensuring proper encapsulation and information hiding.
Depending on the way the child class is derived from the parent class or how many parent classes a child class
inherits, we have the following types of inheritance in c++, namely:
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
ANS- The inheritance in which a single derived class is inherited from a single base class is known as the Single
Inheritance. It is the simplest among all the types of inheritance since it does not include any kind of inheritance
combination or different levels of inheritance. The child class can inherit all the members of the base class
according to the visibility mode (i.e., private, protected, and public) that is specified during the inheritance.
However, it is optional to define the visibility mode during the inheritance. If you do not define it, it sets the
visibility mode to private by default.
ANS- Multiple Inheritance is the concept of the Inheritance in C++ that allows a child class to inherit properties or
behaviour from multiple base classes. Therefore, we can say it is the process that enables a derived class to
acquire member functions, properties, characteristics from more than one base class.
Following is the diagram of the Multiple Inheritances in the C++ programming language.
In the above diagram, there are two-parent classes: Base Class 1 and Base Class 2, whereas there is only one Child
Class. The Child Class acquires all features from both Base class 1 and Base class 2. Therefore, we termed the type
of Inheritance as Multiple Inheritance.
ANS- Multilevel Inheritance in C++ is the process of deriving a class from another derived class. When one class
inherits another class, it is further inherited by another class. It is known as multi-level inheritance.
For example, if we take Grandfather as a base class then Father is the derived class that has features of
Grandfather and then Child is the also derived class that is derived from the sub-class Father which inherits all the
features of Father.
Hierarchical Inheritance in C++ refers to the type of inheritance that has a hierarchical structure of
classes. A single base class can have multiple derived classes, and other subclasses can further inherit
these derived classes, forming a hierarchy of classes. The following diagram illustrates the structure of
Hierarchical Inheritance in C++.
43. What do you mean by hybrid inheritance?
ANS- The inheritance in which the derivation of a class involves more than one form of any
inheritance is called hybrid inheritance. Basically, C++ hybrid inheritance is combination of two
or more types of inheritance. It can also be called multi path inheritance.
Above block diagram shows the hybrid combination of single inheritance and multiple inheritance. Hybrid
inheritance is used in a situation where we need to apply more than one inheritance in a program.
ANS- A nested class is a class that is declared in another class. The nested class is also a member variable of the
enclosing class and has the same access rights as the other members. However, the member functions of the
enclosing class have no special access to the members of a nested class.
A program that demonstrates nested classes in C++ is as follows.
#include<iostream>
using namespace std;
class A {
public:
class B {
private:
int num;
public:
void getdata(int n) {
num = n;
}
void putdata() {
cout<<"The number is "<<num;
}
};
};
int main() {
cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();
return 0;
}
Output
Nested classes in C++
The number is 9
ANS- A virtual function is a member function in the base class that we expect to redefine in derived classes.
Basically, a virtual function is used in the base class in order to ensure that the function is overridden. This
especially applies to cases where a pointer of base class points to an object of a derived class.
46. Explain run time polymorphism.
ANS- In runtime polymorphism, the compiler resolves the object at run time and then it decides which
function call should be associated with that object. It is also known as dynamic or late binding polymorphism.
This type of polymorphism is executed through virtual functions and function overriding. All the methods of
runtime polymorphism get invoked during the run time.
• Function overriding
• Virtual functions
ANS-
An abstract class is a class that is designed to be specifically used as a base class. An abstract class
contains at least one pure virtual function. You declare a pure virtual function by using a pure specifier (=
0) in the declaration of a virtual member function in the class declaration.
ANS- A pure virtual function in c++ is a virtual function for which we do not have an implementation. We do
not write any functionality in it. Instead, we only declare this function. A pure virtual function does not carry
any definition related to its base class. A pure virtual function is declared by assigning a zero (0) in its
declaration. Any class containing one or more pure virtual functions cannot be used to define any object. For
this reason, these classes are known as abstract classes. Classes derived from abstract classes need to
implement the pure virtual functions of these classes.
ANS- An ambiguity can arise when several paths exist to a class from the same base class. This means that a
child class could have duplicate sets of members inherited from a single base class.
- C++ solves this issue by introducing a virtual base class. When a class is made virtual, necessary care is taken
so that the duplication is avoided regardless of the number of paths that exist to the child class.
ANS- A friend function in C++ is a function that is declared outside a class but can access the private and protected
members of the class. There could be situations in programming wherein we want two classes to share their
members. These members may be data members, class functions or function templates. In such cases, we make
the desired function, a friend to both these classes which will allow accessing private and protected data of
members of the class.
Generally, non-member functions cannot access the private members of a particular class. Once declared as a
friend function, the function can access the private and the protected members of these classes.
o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It cannot access the member names directly and has to use an object name and dot membership operator
with the member name.
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
53. Explain how friend function can be used in two or more than two classes.
In C++, a friend function is a function that is granted access to the private and protected members of a
class. It can be declared and defined inside a class, but it is not a member of that class. Friend functions
are useful when you need to allow external functions to access and manipulate the private or protected
members of multiple classes. Here's an explanation of how friend functions can be used in two or more
than two classes:
1. Declaration of Friend Function: To declare a friend function, you need to include a function
prototype inside the class that wants to grant access. This declaration should be placed in the
class definition, typically within the public, private, or protected section, preceded by the friend
keyword. Here's an example:
In this example, we create objects objA and objB of classes ClassA and ClassB, respectively. We then
pass these objects as arguments to the friendFunction to access and manipulate the private members of
both classes.
It's important to note that the friend function needs to be declared as a friend in each class where it
requires access to private or protected members. Additionally, while friend functions provide flexibility
in accessing private members, it's recommended to use them judiciously to maintain encapsulation and
the principle of information hiding.
ANS- Static Member Function in a class is the function that is declared as static because of which function attains
certain properties as defined below:
ANS- Initialization gives a variable an initial value at the point when it is created. Assignment gives a variable a
value at some point after the variable is created.
ANS- Every object in C++ has access to its own address through an important pointer called this pointer.
The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may
be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a class. Only member functions
have a this pointer.
ANS- Errors are the problems that occur in the program due to an illegal operation performed by the user or by
the fault of a programmer.
Exception Handling is the process of handling errors and exceptions such that the normal execution of the
system is not halted. Exception handling in C++ consists of three keywords namely- try, catch, and throw.
59. Explain exception handling mechanism.
• throw– when a program encounters a problem, it throws an exception. The throw keyword helps the
program perform the throw.
• catch– a program uses an exception handler to catch an exception. It is added to the section of a program
where you need to handle the problem. It’s done using the catch keyword.
• try– the try block identifies the code block for which certain exceptions will be activated. It should be
followed by one/more catch blocks.
Suppose a code block will raise an exception. The exception will be caught by a method using try and catch
keywords. The try/catch block should surround code that may throw an exception. Such code is known as
protected code.
Syntax:
The try/catch takes this syntax:
try {
// the protected code
} catch( Exception Name exception1 ) {
// catch block
} catch( Exception Name exception2 ) {
// catch block
} catch( Exception Name exceptionN ) {
// catch block
}
• Although we have one try statement, we can have many catch statements.
• The ExceptionName is the name of the exception to be caught.
• The exception1, exception2, and exceptionN are your defined names for referring to the exceptions.
In C++, multiple exceptions can be handled using multiple catch blocks. When an exception
is thrown, the program searches for a matching catch block to handle that specific type of
exception. By using multiple catch blocks, you can handle different types of exceptions
separately. Here's an explanation with an example:
#include <iostream>
void divide(int numerator, int denominator) {
try {
if (denominator == 0) {
throw "Division by zero is not allowed."; // Throw an exception as a
character string
}
int result = numerator / denominator;
std::cout << "Result: " << result << std::endl;
}
catch (const char* exception) {
std::cout << "Caught exception: " << exception << std::endl;
}
catch (int exception) {
std::cout << "Caught exception: " << exception << std::endl;
}
}
int main() {
try {
divide(10, 2); // No exception
divide(8, 0); // Exception: Division by zero
divide(12, 3); // No exception
}
catch (...) {
std::cout << "Caught an unknown exception." << std::endl;
}
return 0;
}
In this example, we have a function divide() that attempts to perform division between two integers.
Inside the function, we use a try-catch block to handle exceptions.
When divide() is called, the first division (10 / 2) does not cause an exception, so the program prints the
result: "Result: 5".
The second division (8 / 0) causes an exception because it attempts to divide by zero. In this case, we
throw an exception as a character string: "Division by zero is not allowed."
Since the thrown exception is a character string, the first catch block with const char* as the catch type
matches and handles the exception. It prints: "Caught exception: Division by zero is not allowed."
The third division (12 / 3) does not cause an exception, so the program prints the result: "Result: 4".
In the main() function, we have a try-catch block that surrounds the calls to divide(). The catch block
with ... (ellipsis) acts as a catch-all block, which will handle any type of exception that hasn't been caught
explicitly. In this case, it prints: "Caught an unknown exception."
By using multiple catch blocks, we can handle different types of exceptions separately based on their
types. This allows for more fine-grained exception handling and specific error messages based on the
type of exception encountered.
1. Throwing an Exception with Arguments: When throwing an exception, you can include
additional arguments to provide more context about the exception. The arguments can be of
any data type, such as integers, strings, custom objects, etc. You can use the throw keyword
followed by the exception object. Here's an example:
For instances:
2.Catching Exceptions with Arguments: When catching an exception, you can specify the
type of exception along with the argument(s) in the catch block. The catch block will
execute if the thrown exception matches the specified type, and you can access the
exception's argument(s) using the exception object. Here's an example:
In this example, we catch a std::runtime_error exception and access its argument (the error message)
using the what() member function.
3.Defining Custom Exception Classes with Arguments: You can also define your own custom exception
classes that accept arguments by creating a class derived from the standard std::exception or any other
exception class. In your custom exception class, you can define member variables to hold the arguments
and provide appropriate constructors to initialize them. Here's an example:
In this example, we define a custom exception class CustomException derived from std::exception. It
has a member variable message to hold the argument, and we provide a constructor to initialize it. The
what() member function is overridden to return the exception's message.
You can then throw and catch instances of your custom exception class with arguments as shown in the
previous sections.
By throwing and catching exceptions with arguments, you can provide specific information about the
exceptional condition, such as error messages, error codes, or any other relevant data, which can be
helpful for error handling and debugging.