You are on page 1of 55

OOP Sample Question Bank

1. What is Object Oriented Programming?


• Object-oriented programming (OOP) is a style of programming characterized by the
identification of classes of objects closely linked with the methods (functions) with which they
are associated. It also includes ideas of inheritance of attributes and methods. It is a technique
based on a mathematical discipline, called “abstract data types,” for storing data with the
procedures needed to process that data. OOP offers the potential to evolve programming to a
higher level of abstraction.
2. Describe general characteristics of OOP.
• The characteristics of object-oriented programming are as follows:

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.

Abstraction is the essential characteristics of object oriented programming because it hides


complex details from users and provides them the flexibility to change things.
Without abstraction, it is difficult to add functionality without affecting others, and high
complexity arises because of large code bases.
Inheritance
Inheritance means inheriting someone's characteristics. Just like you inherit features and habits
from your parents, it is possible to inherit the data and methods from one class to another.
Combining and inheriting the objects and their properties is one of the most essential and
important characteristics of oops.

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.

Polymorphism exhibits two different behaviors:


Runtime Polymorphism/ Method Overriding: The subclass provides its own implementation of
the function defined in the base class.
For example:
class Person{
void walks(){
System.out.println("Person is walking.");
}
}

class Child extends Person{


void walks(){
System.out.println("Child is walking.");

public static void main(String args[]){


Child obj=new Child();
obj.walks();
}
}

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);
}

private static void show(int x, int y){


System.out.println(x + " and " + y);
}

private static void show(String name){


System.out.println(name);
}

public static void main(String[] args) {


show(7);
show(9, 2);
show("sagar");
}
}
Output:

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

Let's understand both of them using an example.


Static Binding:
In static binding, the property of one object is changed directly without changing the other
property.
class Person{
private void walks(){
System.out.println("person is walking.");

}
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.");
}
}

class Child extends Person{


void walks(){
System.out.println("Child is walking.");

public static void main(String args[]){


Person a=new Child();
a.walks();
}
}

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.

4. What are applications of OOP?

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.

5. Differentiate between procedural oriented programming and object-oriented programming.

Parameter Procedural Programming Object Oriented Programming

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.

Most It prioritizes function over data. It prioritizes data over function.


Important
Attribute

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.”

Note – The keyword “friend” only works for


C++.
Examples Some common examples of Procedural The examples of Object-Oriented
Programming are C, Fortran, VB, and Pascal. Programming languages are Java, C++, VB.NET,
Python, and C#.NET.

6. What are the various features of OOP?


• Same as Q2
7. Explain user-defined data types in C++.
• User Defined Data types in C++ is a type for representing data. The type of data will inform the
interpreter how the programmer will be using the data. A data type can be pre-defined or user-
defined. Examples of pre-defined data types are char, int, float, etc.
As the programming languages allow the user to create their own data types according to their
needs, the data types defined by the users are known as user-defined data types. For example,
arrays, classes, structures, unions, enumerations, pointers, etc. These data types hold more
complexity than pre-defined data types.
8. Explain the structure of a C++ program.
• A structure is a collection of various types of related information under one name. The
declaration of structure forms a template, and the variables of structures are known as
members. All the members of the structure are generally related. The keyword used for the
structure is “struct”.
For example, a structure for student identity having ‘name’, ‘class’, ‘roll_number’, and ‘address’
as a member can be created as follows:

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

structures variables as follows:

stud_id I1, I2;

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

I2.class will access the class of I2

struct stud_id

int class, roll_number;

};

int main ()

struct stud_id entries[10]; // Create an array of structures

entries[0].class = 4; // Access array members

entries[0].roll_number = 20;

cout <<entries[0].class << ", " << entries[0].roll_number;

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:

1. Automatic Memory Allocation (Stack):

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() {

MyClass obj; // Memory for 'obj' is allocated on the stack

// ...

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.

2. Dynamic Memory Allocation (Heap):

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.

MyClass* obj = new MyClass(); // Allocate an object of MyClass on the heap

// ...

delete obj; // Deallocate the memory and invoke the destructor

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
// ...

delete[] objArray; // Deallocate the memory for the array

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.

10. Explain how class members can be accessed.


• In object-oriented programming, class members refer to the properties (variables) and
behaviors (methods) defined within a class. These members can be accessed using various
access modifiers and syntax depending on the programming language. Here are some common
ways to access class members:
Public Access Modifier: Public members are accessible from anywhere, both within the class
itself and from external code. You can access public class members directly using the object of
the class or through inheritance if the class is a base class.
Private Access Modifier: Private members are accessible only within the class that defines them.
They are not directly accessible from external code or derived classes. Private members can be
accessed indirectly through public methods or properties defined within the class.
Protected Access Modifier: Protected members are accessible within the class that defines
them and derived classes. They are not directly accessible from external code. Protected
members can be accessed using the object of the derived class or within the derived class itself.
Internal Access Modifier: Internal members are accessible within the same assembly (a
collection of related classes) but not from external assemblies. The exact way to access internal
members depends on the programming language and project structure.
Static Members: Static members belong to the class itself rather than specific instances of the
class. They are accessed using the class name directly, without creating an object of the class.
Static members are usually accessible using the access modifiers mentioned above.

11. Explain how member functions of class are defined in a program.

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.

Definition Outside the Class:

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.

Calling Member Functions:

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;
}

13. Explain constructor used in C++ with example.

• 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

return type. For example,

class Wall {
public:
// create a constructor
Wall() {
// code
}
};

Here, the function Wall() is a constructor of the class Wall. Notice that the constructor

• has the same name as the class,

• does not have a return type, and

• is public

14. Explain the special characteristics or features of constructors.


• A class constructor is a special member function of a class that is executed whenever we create
new objects of that class. A constructor will have an exact same name as the class and it does
not have any return type at all, not even void. Constructors can be very useful for setting initial
values for certain member variables.

Special characteristics of Constructors:

• They should be declared in the public section

• They do not have any return type, not even void

• They get automatically invoked when the objects are created


• They cannot be inherited though derived class can call the base class constructor

• Like other functions, they can have default arguments

• You cannot refer to their address

15. Explain destructor with example.


• Destructor is an instance member function which is invoked automatically whenever an object is
going to be destroyed. Meaning, a destructor is the last function that is going to be called before
an object is destroyed.
• Destructor is also a special member function like constructor. Destructor destroys the class
objects created by constructor.
• Destructor has the same name as their class name preceded by a tilde (~) symbol.
• It is not possible to define more than one destructor.
• The destructor is only one way to destroy the object create by constructor. Hence destructor
can-not be overloaded.
• Destructor neither requires any argument nor returns any value.
• It is automatically called when object goes out of scope.
• Destructor release memory space occupied by the objects created by constructor.
• In destructor, objects are destroyed in the reverse of an object creation.

16. Explain objects as function arguments.


• we can pass any type of arguments within the member function and there are any numbers of
arguments. In C++ programming language, we can also pass an object as an argument within the
member function of class.

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.

Consider the given program:

#include <iostream>
using namespace std;

class Demo {
private:
int a;

public:
void set(int x)
{
a = x;
}

void sum(Demo ob1, Demo ob2)


{
a = ob1.a + ob2.a;
}

void print()
{
cout << "Value of A : " << a << endl;
}
};

int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;

//assigning values to the data member of objects


d1.set(10);
d2.set(20);

//passing object d1 and d2


d3.sum(d1, d2);
//printing the values
d1.print();
d2.print();
d3.print();

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.

Example 1: C++ Pass Objects to Function

// C++ program to calculate the average marks of two students

#include <iostream>
using namespace std;

class Student {

public:
double marks;

// constructor to initialize marks


Student(double m) {
marks = m;
}
};

// function that has objects as parameters


void calculateAverage(Student s1, Student s2) {
// calculate the average of marks of s1 and s2
double average = (s1.marks + s2.marks) / 2;

cout << "Average Marks = " << average << endl;

int main() {
Student student1(88.0), student2(56.0);

// pass the objects as arguments


calculateAverage(student1, student2);

return 0;
}
Run Code

Output

Average Marks = 72

Here, we have passed two Student objects student1 and student2 as arguments to

the calculateAverage() function.

Example 2: C++ Return Object from a Function

#include <iostream>
using namespace std;

class Student {
public:
double marks1, marks2;
};

// function that returns object of Student


Student createStudent() {
Student student;

// Initialize member variables of Student


student.marks1 = 96.5;
student.marks2 = 75.0;

// print member variables of Student


cout << "Marks 1 = " << student.marks1 << endl;
cout << "Marks 2 = " << student.marks2 << endl;

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.

We have called createStudent() from the main() method.

// Call function
student1 = createStudent();

Here, we are storing the object returned by the createStudent() method in the student1.

18. List and explain the types of constructors.

-> 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.

Syntax of Default Constructor –

class CLASS_NAME

………

public :
CLASS_NAME() //Default constructor

......

//other member functions

};

Example:

#include <iostream>

using namespace std;

//Class Name: Default_construct

class Default_construct

public:

int a, b;

// Default Constructor

Default_construct()

a = 100;

b = 200;

};

int main()
{

Default_construct con; //Object created

cout << "Value of a: " << con.a;

cout<< "Value of b: " << con.b;

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:

class_Name(datatype variable) //Parameterized constructor

………………..

};

Example:

#include <iostream>
using namespace std;

// class name: Rectangle

class Rectangle {

private:

double length;

double breadth;

public:

// parameterized constructor

Rectangle(double l, double b) {

length = l;

breadth = b;

double calculateArea() {

return length * breadth;

};

int main() {

// create objects to call constructors

Rectangle obj1(10,6);

Rectangle obj2(13,8);

cout << "Area of Rectangle 1: " << obj1.calculateArea();

cout << "Area of Rectangle 2: " << obj2.calculateArea();


return 0;

}
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>

using namespace std;

// class name: Rectangle

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() {

return length * breadth;

};

int main() {

// create objects to call constructors

Rectangle obj1(10,6);

Rectangle obj2 = obj1; //copy the content using object

//print areas of rectangles

cout << "Area of Rectangle 1: " << obj1.calculateArea();

cout << "Area of Rectangle 2: " << obj2.calculateArea();

return 0;

19. Explain static class members with example.


• Class members can be declared using the storage class specifier static in the class member list.
Only one copy of the static member is shared by all objects of a class in a program. When you
declare an object of a class having a static member, the static member is not part of the class
object.
A typical use of static members is for recording data common to all objects of a class. For
example, you can use a static data member as a counter to store the number of objects of a
particular class type that are created. Each time a new object is created, this static data member
can be incremented to keep track of the total number of objects.
You access a static member by qualifying the class name using the :: (scope resolution)
operator. In the following example, you can refer to the static member f() of class
type X as X::f() even if no object of type X is ever declared:

struct X {
static int f();
};

int main() {
X::f();
}

20. Explain array of objects.

• 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 −

var fruits = [ "apple", "orange", "mango" ];

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

21. Explain C++ string class.


• C++ String Class Introduced in C++
C++ is based on the OOPs concept; it enables you to represent the string as an object of the C++
String class (std:: string). The class allows you to declare a string variable quickly, and store any
sequence of characters in it. Here is an example of representing a string with the help of the
String class.

#include <iostream>

using namespace std;


int main(){

string greet = "Hello";

cout << "This is a greeting message: ";

cout<<greet<<endl;

Output:

As you can see in the above output, it eliminates the need for declaring an array to hold characters.

22. Explain operator overloading.


• 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 C++, we can make operators work for user-defined classes. This means C++ has the ability to
provide the operators with a special meaning for a data type, this ability is known as operator
overloading. 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.
Example:
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.

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 −

• The increment (++) and decrement (--) operators.


• The unary minus (-) operator.
• The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator
appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as
postfix as well like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix as well as postfix usage.

#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;
}

// overloaded minus (-) operator


Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};

int main() {
Distance D1(11, 10), D2(-5, 11);

-D1; // apply negation


D1.displayDistance(); // display D1

-D2; // apply negation


D2.displayDistance(); // display D2

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.

Syntax of the Binary Operator Overloading


Following is the Binary Operator Overloading syntax in the C++ Programming language.

return_type :: operator binary_operator_symbol (arg)


{
// function definition
}

Here,

return_type: It defines the return type of the function.

operator: It is a keyword of the function overloading.

binary_operator_symbol: It represents the binary operator symbol that overloads a function to perform
the calculation.

arg: It defines the argument passed to the function.

26. Write a program which overloads any relational operator.

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;
}

// overloaded minus (-) operator


Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}

// overloaded < operator


bool operator <(const Distance& d) {
if(feet < d.feet) {
return true;
}
if(feet == d.feet && inches < d.inches) {
return true;
}

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

27. Write a program which operate the assignment operator.

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:

1. A = 5; // use Assignment symbol to assign 5 to the operand A


2. B = A; // Assign operand A to the B
3. B = &A; // Assign the address of operand A to the variable B
4. A = 20 \ 10 * 2 + 5; // assign equation to the variable A

Simple Assignment Operator (=):

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';

Let's create a program to use the simple assignment operator in C.

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

The value of n1: 5


The value of n2: 5
The value of c: 10
The value of x: 15

28. Explain rules of operator overloading.


• Operator overloading -- is the creation of new versions of these operators for use with user-
defined types.

• It is not as difficult as it sounds. Some things to note:


o An operator in C++ is just a function that is called with special notation (usually more
intuitive or familiar notation). Overloading an operator simply involves writing a
function.
o C++ already does some operator overloading implicitly on built-in types. Consider the
fact that the + operator already works for ints, floats, doubles, and chars. There is really
a different version of the + operator for each type.
o Operator overloading is done for the purpose of using familiar operator notation
on programmer-defined types (classes).

Some rules regarding operator overloading

• Overloading an operator cannot change its precedence.


• Overloading an operator cannot change its associativity.
• Overloading an operator cannot change its "arity" (i.e. number of operands)
• It is not possible to create new operators -- only new versions of existing ones.
• Operator meaning on the built-in types cannot be changed.

29. Explain array of pointers.

• 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:

int *ptr[5]; // array of 5 integer pointer.

30. Explain dynamic memory allocation and deallocation operators.


• Dynamic Memory Allocation
Dynamic memory allocation (i.e., allocation of memory) can be performed using ‘new’ operator.
‘new’ Operator
The ‘new’ operator is used to dynamically allocate the memory for objects which returns 4
pointers to it.
Syntax
pointer_variable = new datatype;
Example
ptr = new int;
Here, ‘ptr’ is a pointer variable of type int created by using a new operator.
The allocated memory is large such that the object can be accommodated for the specified data type. If
the requested memory is not available then it either returns a ‘NULL’ pointer or an exception is
generated. But, usually in C++, it generates an exception in case of unsuccessful allocation request. This
exception should be handled by the program, otherwise it results in termination of program.

Dynamic Memory Deallocation


Deallocation of memory can be performed by using delete operators.
‘delete’ Operator
The delete operator is used to deallocate i.e., it releases the memory which was allocated by
the new operator through its pointer. The memory is then released so that it can be utilized by some
other object.
Syntax
delete pointer_variable;
Example
delete ptr;
Here,'ptr' is the pointer variable which was allocated by new operator, thereby, destroying the object
using delete. operator.
When delete statement is called with an invalid pointer then it destroys the allocation system which
might probably result in program crash.

31. Explain pointers to objects with example.

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.

Inheritance is one of the key features of Object-oriented programming in C++. It allows us to

create a new class (derived class) from an existing class (base class).

The derived class inherits the features from the base class and can have additional

features of its own. For example,

class Animal {
// eat() function
// sleep() function
};

class Dog : public Animal {


// bark() function
};

Here, the Dog class is derived from the Animal class. Since Dog is derived from Animal,

members of Animal are accessible to Dog.

Inheritance in C++

Notice the use of the keyword public while inheriting Dog from Animal.

class Dog : public 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.

33. Explain the derived class declaration.

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

class DerivedClass : public BaseClass{

// 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.

/* C++ program to find Area using Function Overloading */

#include<iostream>

using namespace std;

int area(int);

int area(int,int);

float area(float);

float area(float,float);

int main()

int s,l,b;

float r,bs,ht;

cout<<"Enter side of a square:";

cin>>s;

cout<<"Enter length and breadth of rectangle:";

cin>>l>>b;

cout<<"Enter radius of circle:";

cin>>r;

cout<<"Enter base and height of triangle:";

cin>>bs>>ht;

cout<<"Area of square is"<<area(s);

cout<<"\nArea of rectangle is "<<area(l,b);

cout<<"\nArea of circle is "<<area(r);

cout<<"\nArea of triangle is "<<area(bs,ht);

}
int area(int s)

return(s*s);

int area(int l,int b)

return(l*b);

float area(float r)

return(3.14*r*r);

float area(float bs,float ht)

return((bs*ht)/2);

OUTPUT : :

/* C++ program to find Area using Function Overloading */

Enter side of a square:2

Enter length and breadth of rectangle:3 6

Enter radius of circle:3

Enter base and height of triangle:4 4

Area of square is4

Area of rectangle is 18

Area of circle is 28.26


Area of triangle is 8

37. Explain the accessibility of the members in inheritance.

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.

38. List the types of inheritance.

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

39. Explain single 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.

40. Explain multiple inheritance.

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.

41. Explain multilevel 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.

42. Explain hierarchical inheritance.

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.

44. Explain classes within classes with an example.

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

45. Explain virtual function in detail with syntax and example.

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.

The implementation of run time polymorphism can be achieved in two ways:

• Function overriding

• Virtual functions

47. Compare early binding and late binding.

Early Binding vs Late Binding


The process of using the class information to resolve The process of using the object to resolve
method calling that occurs at compile time is called method calling that occurs at run time is called
Early Binding. the Late Binding.
Time of Binding
Early Binding happens at compile time. Late Binding happens at run time.
Functionality
Early Binding uses the class information to resolve Late Binding uses the object to resolve method
method calling. calling.
Synonyms
Early Binding is also known as static binding.. Late Binding is also known as dynamic binding.
Occurrence
Overridden methods are bonded using late
Overloading methods are bonded using early binding.
binding.
Execution Speed
Execution speed is faster in early binding. Execution speed is lower in late binding.

48. Explain abstract classes.

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.

49. What is pure virtual function?

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.

50. What are virtual base 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.

51. Explain friend function.

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.

52. Explain the features of friend function.

ANS- Characteristics of a Friend function:

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 can be invoked like a normal function without using the object.

o It cannot access the member names directly and has to use an object name and dot membership operator
with the member name.

o It can be declared either in the private or the public part.

#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, friendFunction is declared as a friend function within ClassA.


2. Definition of Friend Function: The friend function is defined outside the class, just like any other
regular function. It can access the private and protected members of the class(es) it is declared
as a friend in. Here's an example:
In this example, friendFunction is defined outside both ClassA and ClassB, and it can access and
manipulate the private members of both classes.
3. Usage of Friend Function: Once the friend function is declared and defined, it can be called and
used like any other function, providing the necessary objects as arguments. 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.

54. Explain static data members.


ANS- A static data member in C++ is a data member defined in a class that is not instantiated with each object
created of the class. Data members defined in a class are usually instantiated with every object created of the
class. That is, each object of the class will have their own instances or copies of the data members defined in the
class. However, if a data member is initialized with the static keyword, that data member will not be instantiated
and there shall exist only one copy of that data member for all objects or instances of the class.

55. Explain static member functions.

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:

o A static member function is independent of any object of the class.


o A static member function can be called even if no objects of the class exist.
o A static member function can also be accessed using the class name through the scope resolution
operator.
o A static member function can access static data members and static member functions inside or outside of
the class.
o Static member functions have a scope inside the class and cannot access the current object pointer.
o You can also use a static member function to determine how many objects of the class have been created.

56. What is the difference between assignment and copy initialization?

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.

57. Explain THIS pointer.

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.

58. Explain exception handling.

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.

ANS- Exception handling in C++ revolves around these three keywords:

• 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.

60. Explain multiple exception with example.

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.

61. Explain exception with arguments.


In C++, exceptions can be thrown and caught with additional arguments to provide more information
about the exceptional condition. These arguments can be of any data type, allowing you to pass specific
information related to the exception being thrown. Here's an explanation of how exceptions with
arguments work in C++:

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:

In this example, we throw a std::runtime_error exception with a descriptive error


message as an argument.

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.

You might also like