0% found this document useful (0 votes)
11 views

OOP QUESTION With Solution

Object oriented programing question with solutions

Uploaded by

lienaxmagician
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

OOP QUESTION With Solution

Object oriented programing question with solutions

Uploaded by

lienaxmagician
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

OBJECT ORIENTED PROGRAMMING USING C++

SOLVED PAPER 2021 & 2022


Two Marks Questions

Q1. What is abstract class? (2021)


What do you understand by an abstract class? Explain (2022)

Ans: An abstract class in C++ is one that has at least one pure virtual function.
An abstract class is a class that is designed to be specifically used as a base class.
We cannot create object of an abstract class. It can only be inherited by other class.

Q2. What is the purpose of defining a destructor function?

Ans: Destructor is a special type of function which destroys the object as soon as the scope
of object ends.
The destructor is called automatically by the compiler when the object goes out of
scope.
The syntax for destructor is same as that for the constructor.
The name of destructor is same as class name, with a tilde ~ sign as prefix to it.
Destructors will never have any arguments.

Q3. What is dynamic memory allocation? (2021)


What is the difference between static and dynamic memory allocation? (2022)

Ans: Static allocation or compile-time allocation - Static memory allocation means


providing space for the variable. The size and data type of the variable is known, and it
remains constant throughout the program.
Dynamic allocation or run-time allocation - The allocation in which memory is allocated
dynamically. In this type of allocation, the exact size of the variable is not known in
advance. Pointers play a major role in dynamic memory allocation.

Q4. What is function overriding?


Differentiate between function overloading and overriding.

Ans: When the base class and derived class have member functions with exactly the same
name, same return-type, and same arguments list, then it is said to be function overriding.

Difference between Function Overloading and Function Overriding in C++

Function Overloading Function Overriding

In function overloading, two or more Function overriding permit us to redefine a


functions can own the same name, but the method with the same name and signature
parameters will be different.

There is no requirement of the inheritance In function overriding, we need an


concept here. inheritance concept.

In the case of function overloading, the In the case of function overriding, the
signatures should be different. signatures should be the same.

[TYPE HERE] 1|PAGE PREPARED BY: VIPIN KUMAR SARAOGI


We can use it as an example of compile We can use it as an example of run time
time polymorphism. polymorphism.

Q5. Define this pointer.


What do you mean by this pointer? Explain using an example.

Ans: “this” pointer is a constant pointer that holds the memory address of the current
object. “this” pointer is not available in static member functions as static member
functions can be called without any object (with class name).

Following are the situations where “this” pointer is used:

1) When local variable’s name is same as member’s name


2) To return reference to the calling object

Example:
#include<iostream.h>
using namespace std;
class person
{
private :
int age;
public:
void setage(int age)
{
this->age = age;
}
void showage()
{
cout << this->age<<endl;
}
};

int main()
{
person anil;
anil.setage(24);
anil.showage();
return 0;
}

Q6. What is virtual class?

Ans: Virtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using multiple
inheritances.

[TYPE HERE] 2|PAGE PREPARED BY: VIPIN KUMAR SARAOGI


Q7. Name all access modifiers?
Discuss on various access specifiers.

Ans: The Access Specifiers help to achieve Data Hiding in C++.Basically, access
specifiers are used to hide/show data from outside world.

Types of Access Modifiers


C++ has three different types of access modifiers –
1. Public
2. Private
3. Protected

Access Specifiers in C++

Specifier Within Same Class In Derived Class Outside the Class


Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes

Q8. What is exception?

Ans: Exceptions are runtime errors that a program encounters during its execution.
There are two types of exceptions:
1) Synchronous
2) Asynchronous

C++ provides the following specialized keywords for this purpose:

try: Represents a block of code that can throw an exception.


catch: Represents a block of code that is executed when a particular exception is
thrown.
throw: Used to throw an exception. Also used to list the exceptions that a function
throws but doesn’t handle itself.

Q9. What is polymorphism?

Ans: Polymorphism means many forms. It is an object-oriented programming concept


that refers to the ability of a variable, function, or object to take on multiple forms, which
are when the behavior of the same object or function is different in different contexts.
Polymorphism can occur within the class and when multiple classes are related by
inheritance.

Q10. What is template?


What is generic programming? Explain.

Ans: Templates in C++ promote generic programming, meaning the programmer does
not need to write the same function or method for different parameters.
The idea behind the templates in C++ is very simple. We pass the data type as a parameter, so
we don’t need to write the same code for different data types.

[TYPE HERE] 3|PAGE PREPARED BY: VIPIN KUMAR SARAOGI


Types of Templates in C++
There are two types of templates in C++
1) Function template
2) Class templates

Q11. Explain structure as user defined data type.

Ans: A structure is a user-defined data type in C/C++. A structure creates a data type that
can be used to group items of possibly different types into a single type.
The ‘struct’ keyword is used to create a structure. The general syntax to create a
structure is as shown below:

struct structureName{
member1;
member2;
member3;
.
.
.
memberN;
};

Q12. Explain difference between static binding and dynamic binding.

Ans: There are two types of binding in C++:


1) Static or early binding
2) Dynamic or late binding.

Differences between static and dynamic binding in C++.

• The static binding happens at the compile-time, and dynamic binding happens at the
runtime. Hence, they are also called early and late binding, respectively.
• In static binding, the function definition and the function call are linked during the
compile-time, whereas in dynamic binding, the function calls are not resolved until
runtime. So, they are not bound until runtime.
• Static binding happens when all information needed to call a function is available at the
compile-time. Dynamic binding happens when the compiler cannot determine all
information needed for a function call at compile-time.
• Static binding can be achieved using the normal function calls, function overloading,
and operator overloading, while dynamic binding can be achieved using the virtual
functions.

Q13. What is pure virtual function? Explain.

Ans: A pure virtual function is a virtual function in C++ for which we need not to write
any function definition and only we have to declare it. It is declared by assigning 0 in the
declaration.
An abstract class is a class in C++ which have at least one pure virtual function.

[TYPE HERE] 4|PAGE PREPARED BY: VIPIN KUMAR SARAOGI


Example:
#include<iostream>
using namespace std;
class B {
public:
virtual void s() = 0; // Pure Virtual Function
};

Q14. Describe the functionality of


a) ofstream
b) ifstream
c) fstream
Ans:
a) ofstream Stream class to write on files
b) ifstream Stream class to read from files
c) fstream Stream class to both read and write from/to files.

8 Marks Questions

Q1. List out difference between procedure-oriented programming and Object-


oriented programming? (2021)
What do you understand by object oriented programming? What are it’s
advantages over procedure oriented programming? Explain the features of
object oriented programming paradigm. (2022)

Ans: Procedural Programming


Procedural programs consist of a series of steps or procedures that take place one after
the other. The programmer determines the exact conditions under which a procedure
takes place, how often it takes place, and when the program stops. In the procedure-
oriented approach, the problem is viewed as the sequence of things to be done such as
reading, calculating and printing such as COBOL, FORTRAN and C. The primary
focus is on functions. A typical structure for procedural programming is shown in
figure below.

[TYPE HERE] 5|PAGE PREPARED BY: VIPIN KUMAR SARAOGI


The technique of hierarchical decomposition has been used to specify the tasks to be
completed for solving a problem. Procedure oriented programming basically consists of
writing a list of instructions for the computer to follow, and organizing these instructions
into groups known as functions. We normally use flowcharts to organize these actions and
represent the flow of control from one action to another.

Some Characteristics exhibited by procedure-oriented programming are:

• Emphasis is on doing things (algorithms).


• Large programs are divided into smaller programs known as functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Functions transform data from one form to another.
• Employs top-down approach in program design.

Characteristics of Object Oriented Paradigm

• Emphasis is on data rather than procedure.


• Programs are divided into what are known as objects.
• Data is hidden and cannot be accessed by external functions.
• Objects may communicate with each other through functions.

Benefits/advantages of OOP

OOP offers several benefits to both the program designer and the user. Object-Orientation
contributes to the solution of many problems associated with the development and quality
of software products. The new technology promises greater programmer productivity,
better quality of software and lesser maintenance cost.

The principal advantages are:

• Through inheritance, we can eliminate redundant code extend the use of existing
Classes.
• We can build programs from the standard working modules that communicate with one
another, rather than having to start writing the code from scratch. This leads to saving
of development time and higher productivity.
• The principle of data hiding helps the programmer to build secure program that cannot
be invaded by code in other parts of a programs.
• It is possible to have multiple instances of an object to co-exist without any interference.
• It is possible to map object in the problem domain to those in the program.
• It is easy to partition the work in a project based on objects.
• The data-centered design approach enables us to capture more detail of a model can
implemental form.
• Object-oriented system can be easily upgraded from small to large system.
• Message passing techniques for communication between objects makes to interface
descriptions with external systems much simpler.
• Software complexity can be easily managed.

[TYPE HERE] 6|PAGE PREPARED BY: VIPIN KUMAR SARAOGI


Difference between Procedural approach and Object oriented approach

Procedural Oriented Programming Object-Oriented Programming

In procedural programming, the program is In object-oriented programming, the


divided into small parts called functions. program is divided into small parts
called objects.

Procedural programming follows a top- Object-oriented programming follows


down approach. a bottom-up approach.

There is no access specifier in procedural Object-oriented programming has access


programming. specifiers like private, public, protected,
etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have Object-oriented programming provides


any proper way of hiding data so it is less data hiding so it is more secure.
secure.

In procedural programming, overloading is Overloading is possible in object-oriented


not possible. programming.

In procedural programming, there is no In object-oriented programming, the


concept of data hiding and inheritance. concept of data hiding and inheritance is
used.

In procedural programming, the function is In object-oriented programming, data is


more important than the data. more important than function.

Procedural programming is based on Object-oriented programming is based on


the unreal world. the real world.

Procedural programming is used for Object-oriented programming is used for


designing medium-sized programs. designing large and complex programs.

Code reusability absent in procedural Code reusability present in object-


programming, oriented programming.

Examples: C, FORTRAN, Pascal, Basic, Examples: C++, JAVA


etc.

[TYPE HERE] 7|PAGE PREPARED BY: VIPIN KUMAR SARAOGI


Q2. Write a C++ program to swap two numbers using pointers.

Ans:
#include <iostream.h>
using namespace std;

void swap(int*, int*); // function declaration with pointer as parameters

int main()
{

int a = 1, b = 2; // initialize variables

cout << "Before swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;

swap(&a, &b); // call function by passing variable addresses

cout << "\nAfter swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

void swap(int* n1, int* n2) // function definition to swap numbers


{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}

Q3. Explain function overloading in C++ with an example.

Ans: Function Overloading


It is a way of implementing compile time polymorphism. Function overloading is also
known as compile time polymorphism.
Function overloading means two or more functions can have the same name but either the
number of arguments or the data type of arguments has to be different. Return type has no
role because function will return a value when it is called and at compile time compiler will
not be able to determine which function to call.
If any class have multiple functions with same names but different parameters then they
are said to be overloaded. Function overloading allows you to use the same name for
different functions, to perform, either same or different functions in the same class.
Function overloading is usually used to enhance the readability of the program. If you have
to perform one single operation but with different number or types of arguments, then you
can simply overload the function.

[TYPE HERE] 8|PAGE PREPARED BY: VIPIN KUMAR SARAOGI


Ways to overload a function
• By changing number of Arguments.
• By having different types of argument.

Program example:

#include<iostream.h>
#include<conio.h>
class funoverload
{
public:
void print(int x, int y)
{
cout<<”sum=”<<x+y;
}
void print(int x, int y, int z)
{
cout<<”average=”<<(x+y+z)/3.0;
}
};
void main()
{
funoveroad obj;
obj.print(7,5);
obj.print(7,6,5);
getch();
}

Q4. Write a C++ program to overload + operator to add two complex numbers.

Ans: Program to overload + operator to add two complex numbers

class complex
{
float real,img;
public:
complex() //Default constructor
{
real=0;
img=0;
}
complex(float r, float i) //Parameterized constructor
{
real=r;
img=i;
}
void show()
{
cout<<real<<”+I”< <img;
}
complex operator +(complex &p) // function to overload + operator
{
complex w;
[TYPE HERE] 9|PAGE PREPARED BY: VIPIN KUMAR SARAOGI
w.real=real+q.real;
w.img=img+q.img;
return w;
}
};

void main()
{
complex s(3,4);
complex t(4,5);
complex m;
m=s+t; // Using + operator to add two complex numbers
s.show();
t.show();
m.show();
}

Q5. Explain multiple inheritance in C++ with example.

Ans: A class can inherit the attributes of two or more classes. This mechanism is known as
‘MULTIPLE INHERITENCE’. Multiple inheritance allows us to combine the features of
several existing classes as a starring point for defining new classes. It is like the child
inheriting the physical feature of one parent and the intelligence of another. The syntax of
the derived class is as follows:
One class being derived from multiple parent classes.
In this type of inheritance a single derived class may inherit from two or more than two
base classes.

Syntax of multiple inheritance:


class A
{
// data & functions
};
class B
{
// data & functions
};
class C: public B, public A
{
// data & functions
};

[TYPE HERE] 10 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Example of Multiple Inheritance

#include<iostream.h>
#include<conio.h>
class input
{
protected:
int n;
public:
void getdata()
{
cout<<”enter any no”;
cin>>n;
}
};
class factorial
{
protected:
int facto;
public:
int fact(int n);
};
int factorial::fact(int n)
{
int i=1;
while(n>1)
{
i=i*n;
n--;
}
return i;
}
class output : public input, public factorial
{
public:
void putdata()
{
cout<<”Factorial=”<<fact(5);
}
};

void main()
{
output obj;
obj.getdata();
obj.putdata();
getch();
}

[TYPE HERE] 11 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Q6. Define virtual function. Explain the mechanism of virtual function.

Ans: A C++ virtual function is a member function in the base class that you redefine in a
derived class. It is declared using the virtual keyword. Run time polymorphism is
implemented through virtual function.
• It is used to perform dynamic binding or late binding on the function.
• There is a necessity to use the single pointer to refer to all the objects of the different
classes. So, we create the pointer to the base class that refers to all the derived
objects. But, when base class pointer contains the address of the derived class
object, always executes the base class function. This issue can only be resolved by
using the 'virtual' function.
• A 'virtual' is a keyword preceding the normal declaration of a function.
• When the function is made virtual, C++ determines which function is to be invoked
at the runtime based on the type of the object pointed by the base class pointer.

Example:
#include <iostream.h>
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B : public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}

Q7. What is the use of NEW & DELETE operator in C++? Explain with example.

Ans: NEW operator is used to dynamically allocate memory on the heap. Memory
allocated by new must be deallocated using delete operator.

Syntax of new is:

p_var = new type name;

where p_var is a previously declared pointer of type typename.


typename can be any basic data type.

[TYPE HERE] 12 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


new can also create an array:
p_var = new type [size];

In this case, size specifies the length of one-dimensional array to create.

Example 1:

int *p;
p=new int;

It allocates memory space for an integer variable. And allocated memory can be released
using following statement.

delete p;

Example 2:

int *a;
a = new int[100];

It creates a memory space for an array of 100 integers. a[0] will refer to the first element,
a[1] to the second element, and so on. And to release the memory following statement can
be used:

delete [] a;

Example:
#include<iostream.h>
using namespace std;
class Box
{
int *p;
public:
Box()
{
p= new int[4];
cout << "Memeory allocated!" <<endl;
}
~Box()
{
delete [] p;
cout << "Memeory Deallocated!" <<endl;
}
};
int main( )
{
Box myBoxArray;
return 0;
}

[TYPE HERE] 13 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Q8. Write a program to pass the structure to a function. Explain each and every
step-in detail.

Ans: We can pass a structure variable to a function as argument like we pass any other
variable to a function. Structure variable is passed using call by value. We can also pass
individual member of a structure as function argument.

Example:

#include<iostream.h>
struct student
{
char *name;
int age;
float per;
};
void display(struct student o)
{
cout<<”ENETR NAME”;
cin>>o.name;
cout<<”ENTER AGE”;
cin>>o.age;
cout<<”ENTER PERCENTAGE”;
cin>>o.per;
}
int main()
{
struct student o={"RAM",25,75.5};
display(o);
return 0;
}

This program demonstrates how to pass a structure as an argument to a function in


C++.
• A structure called "student" is defined with three members: name, age, and per. These
members are defined as a pointer to a character (string), an integer, and a floating-point
number, respectively.
• In the main function, an instance of the "student" structure is created with the name
"RAM", age 25, and percentage 75.5.
• The program defines a function called "display()" which takes a single argument of
the "student" structure type. Inside the function, the members of the structure are
accessed and displayed using the cout function.
• In the main function, the structure instance is passed as an argument to
the "display()" function. When the function is called, a copy of the structure is passed to
the function, so any changes made to the structure inside the function will not affect the
original structure.
• In the display function the members of the structure are accessed using the
dot operator(.) and the cout function is used to print the values.
• Finally, the program ends with a return 0 statement, which indicates that the program
has executed successfully.

[TYPE HERE] 14 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Q9. What is friend function? Explain characteristics of friend function using an
example.

Ans: It is a special type of function in C++. Friend function is function that is not member
of any class but can access private data of that class whose friend is that function. Because
they are not members of any class, you should not call them using the dot operator.
If a function is defined as a friend function then, the private and protected data of class can
be accessed from that function. The complier knows a given function is a friend function
by its keyword friend. The declaration of friend function should be made inside the body
of class (can be anywhere inside class either in private or public section) starting with
keyword friend.

Syntax:

class class_name {
...... .... ........
friend return_type function_name(argument/s);
...... .... ........
};

Example: To find the average of two numbers using friend function.

#include<iostream.h>
#include<conio.h>
class base
{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float avg(base ob); // friend function
};

float avg(base ob) // definition of friend function


{
return float(ob.val1+ob.val2)/2;
}

void main()
{
clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "< <avg(obj); // calling friend function
getch();
}

[TYPE HERE] 15 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Q10. Define super and sub class. Explain the concept of public, private and protected
inheritance.

Ans: Inheritance is a feature or a process in which, new classes are created from the
existing classes. The new class created is called “derived class” or “sub class” and the
existing class is known as the “base class” or “super class”. The derived class now is said
to be inherited from the base class.

• Sub Class: The class that inherits properties from another class is called Subclass
or Derived Class.
• Super Class: The class whose properties are inherited by a subclass is called Base
Class or Superclass.

Modes of Inheritance: There are 3 modes of inheritance.


1. Public Mode: If we derive a subclass from a public base class. Then the public
member of the base class will become public in the derived class and protected
members of the base class will become protected in the derived class.
2. Protected Mode: If we derive a subclass from a Protected base class. Then both
public members and protected members of the base class will become protected
in the derived class.
3. Private Mode: If we derive a subclass from a Private base class. Then both
public members and protected members of the base class will become Private in
the derived class.

Q11. Give the description of the following stream mode flags:


a) std::ios::app
b) std::ios::ate
c) std::ios::binary
d) std::ios::noreplace
Ans: Mode – There different mode to open a file.
Mode Description

iso::app File opened in append mode

iso::ate File opened in append mode but read and write performed at the end
of the file.

iso::binary File opened in binary mode

iso::trunc File opened in truncate mode

iso::noreplace The file opens only if it doesn’t exist

[TYPE HERE] 16 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Q12. Describe the mechanism of accessing data members and member functions in
the following case-
a) Inside the main program
b) Inside the member function of same class
Ans:
a) Inside the main program
The data members and member functions of class can be accessed using the dot(‘.’) operator
with the object. For example if the name of object is obj and you want to access the member
function with the name printName() then you will have to write obj.printName() .
b) Inside the member function of same class
All the data members and member functions of a class are accessible from the member function
of the same class.

15 Marks Questions
Q1. What are the different types of constructors in C++? Illustrate with an example.
(2021)
What is constructor? List various types of constructors and describe with the
help of suitable example. (2022)

Ans: A constructor is a special member function of a class that is executed whenever we


create new objects of that class.
A constructor will have exactly same name as the class.
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 or
dynamically allocating memory to a variable.

Types of Constructors:
1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor

Default Constructor
Default constructor is the constructor which doesn't take any argument. It has no parameter.

Parameterized Constructor
These are the constructors with parameter. Using this Constructor you can provide different
values to data members of different objects, by passing the appropriate values as argument.

Copy Constructor
These are special type of Constructors which takes an object as argument, and is used to copy
values of data members of one object into other object.

Example:
class cube
{
int side;
public:
cube() //default constructor
{
side=10;
}
[TYPE HERE] 17 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI
cube(int x) //parameterized constructor
{
side=x;
}
cube(cube &x) //copy constructor
{
side=x.side;
}
void display()
{
cout<<side;
}
}; //end of class

void main()
{
cube c1; //default constructor called
cube c2(5); //parameterized constructor called
cube c3(c2); //copy constructor called
c1.display();
c2.display();
c3.display();
}

Q2. Explain types of inheritance in C++ with suitable example. (2021)


What is inheritance? What are the various forms of inheritance? Explain each
with the help of suitable example. (2022)

Ans: INHERITANCE
The mechanism that allows us to extend the definition of a class without making any physical
changes to the existing class is inheritance.
Inheritance lets you create new classes from existing class. Any new class that you create from
an existing class is called derived class; existing class is called base class.
The inheritance relationship enables a derived class to inherit features from its base class.
Furthermore, the derived class can add new features of its own. Therefore, rather than create
completely new classes from scratch, you can take advantage of inheritance and reduce
software complexity.

Types of Inheritance

Simple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from
one base class.
Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from
multiple base class(es)
Hierarchical Inheritance: It is the inheritance hierarchy wherein multiple subclasses inherit
from one base class.
Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class
for other classes.
Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other
four types of inheritance.

[TYPE HERE] 18 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Simple inheritance
In simple inheritance, there is only one base class and has only one derived class. In this type
of inheritance one derived class inherits from only one base class. It is the simplest form of
Inheritance.

Syntax of simple inheritance:


class Base
{
// data & functions
};
class Derv: public Base
{
// data & functions
};

Multi-level inheritance
In multi-level inheritance, there will be a chain of inheritance with a class derived from only
one parent and will have only one child class.
In this type of inheritance the derived class inherits from a class, which in turn inherits from
some other class. The Super class for one, is sub class for the other.

Syntax of multi-level inheritance:


class A
{
// data & functions
};
class B: public A
{
// data & functions
};
class C: public B
{
// data & functions
};

[TYPE HERE] 19 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Multiple inheritance
One class being derived from multiple parent classes. In this type of inheritance a single
derived class may inherit from two or more than two base classes.

Syntax of multiple inheritance:


class A
{
// data & functions
};
class B
{
// data & functions
};
class C: public B, public A
{
// data & functions
};

Hierarchical inheritance
Many classes deriving from one class.
In this type of inheritance, multiple derived classes inherits from a single base class.

Syntax of hierarchical inheritance:


class A
{
// data & functions
};
class B: public A
{
// data & functions
};
class C: public A
{
// data & functions
};

[TYPE HERE] 20 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Hybrid inheritance
It is a mixture of 2 or more of above types of inheritance. There is no pattern of deriving from
classes.
Hybrid Inheritance is combination of Hierarchical and Multilevel Inheritance.

Syntax of hybrid inheritance:


class A
{
// data & functions
};
class B : public A
{
// data & functions
};
class C: public A
{
// data & functions
};
class D: public B, public C
{
// data & functions
};

Q3. What is an exception? Explain exception-handling mechanism with suitable


example.
Explain try, throw, and catch constructs with their syntax. Also, write a
program to implement it.

Ans: An exception is a problem that arises during the execution of a program. A C++ exception
is a response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.

1) throw: A program throws an exception when a problem shows up. This is done using
a throw keyword.
2) catch: A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
3) try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using a combination
of the try and catch keywords. A try/catch block is placed around the code that might

[TYPE HERE] 21 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


generate an exception. Code within a try/catch block is referred to as protected code, and the
syntax for using try/catch looks like the following:

try
{
// protected code
}
catch( ExceptionName e1 )
{
// catch block
}
catch( ExceptionName e2 )
{
// catch block
}
catch( ExceptionName eN )
{
// catch block
}

You can list down multiple catch statements to catch different type of exceptions in case your
try block raises more than one exception in different situations.
An exception is thrown by using the throw keyword from inside the try block. Exception
handlers are declared with the keyword catch, which must be placed immediately after the try
block:

#include <iostream>
using namespace std;
int main () {
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
return 0;
}

Q4. Explain run time polymorphism, its advantages and how it is implemented in
C++. (2021)
What is dynamic binding? Explain the concept of virtual function with the help
of an example. (2022)

Ans: This is one of the most important topics in C++. Runtime polymorphism is also known
as dynamic polymorphism or late binding. In runtime polymorphism, the function call is
resolved at run time.
In a Runtime polymorphism, functions are called at the time the program execution. Hence, it
is known as late binding or dynamic binding.
It is achieved by using virtual functions and pointers. It provides slow execution as it is known
at the run time. Thus, It is more flexible as all the things executed at the run time.

[TYPE HERE] 22 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


A virtual function is declared by keyword virtual. The return type of virtual function may be
int, float, void.
A virtual function is a member function in the base class. We can redefine it in a derived
class. It is part of run time polymorphism. The declaration of the virtual function must be in
the base class by using the keyword virtual. A virtual function is not static.
The virtual function helps to tell the compiler to perform dynamic binding or late binding on
the function.
If it is necessary to use a single pointer to refer to all the different classes’ objects. This is
because we will have to create a pointer to the base class that refers to all the derived objects.
When we declare a virtual function, the compiler determines which function to invoke at
runtime.

Example:
#include <iostream>
class A
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}

Q5. What is file? Write various file handling functions in C++. How file handling is
done in C++? Explain with example.

Ans: File Handling concept in C++ language is used for store a data permanently in
computer. Using file handling we can store our data in Secondary memory (Hard disk).

File: The information / data stored under a specific name on a storage device, is called a file.

Why use File Handling


• For permanent storage.
• The transfer of input - data or output - data from one computer to another can be
easily done by using files.

[TYPE HERE] 23 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Functions use in File Handling

Function Operation
open() To create a file
close() To close an existing file
get() Read a single character from a file
put() Write a single character in file.
read() Read data from file
write() Write data into file.

Opening a file

Opening File Using open()

Stream-object.open(“filename”, mode)

ofstream outFile;
outFile.open("sample.txt");
ifstream inFile;
inFile.open("sample.txt");

File Opening mode

Mode Meaning Purpose


ios :: out Write Open the file for write only.
ios :: in read Open the file for read only.
ios :: app Appending Open the file for appending data to end-of-
file.
ios :: ate Appending take us to the end of the file when it is
opened.

C++ program to write and read values using file


#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main()
{
char name[30];
int age;
fstream file;
file.open("aaa.txt",ios::out);
if(!file)
{
cout<<"Error in creating file.."<<endl;
}
cout<<"\nFile created successfully."<<endl;

cout<<"Enter your name: ";


cin.getline(name,30);
cout<<"Enter age: ";
cin>>age;
//write into file
file<<name<<" "<<age<<endl;
[TYPE HERE] 24 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI
file.close();
cout<<"\nFile saved and closed succesfully."<<endl;
//reopen file in input mode and read data
file.open("aaa.txt",ios::in);
if(!file)
{
cout<<"Error in opening file..";
}
file>>name;
file>>age;
cout<<"Name: "<<name<<",Age:"<<age<<endl;
getch();
}

Q6. What is operator overloading? How will you overload binary and unary
operators? Discuss both process with the help of programming implementation.

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

Rules for Operator Overloading


• Existing operators can only be overloaded, but the new operators cannot be overloaded.
• The overloaded operator contains atleast one operand of the user-defined data type.
• We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators.
• When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
• When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit
arguments.

Operator that cannot be overloaded are as follows:


• Scope operator (::)
• Sizeof
• member selector(.)
• member pointer selector(*)
• ternary operator(?:)

Syntax of Operator Overloading


return_type class_name : : operator op(argument_list)
{
// body of the function.
}

Example: A C++ program to overload a unary decrement operator


#include <iostream>
using namespace std;
class OverLoad
{
private:
int a,b;
[TYPE HERE] 25 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI
void input()
{
cout << "Enter the first number : ";
cin >> a;
cout<< "Enter the second number : ";
cin >> b; }
void operator-- () // Overload the prefix decrement operator

{
a= --a;
b= --b;
}
void output()
{
cout<<"The decremented elements of the object are: "<<endl<< a<<" and "
<<b;
}
};
int main()
{
OverLoad obj;
obj.input();
--obj;
obj.output();
return 0;
}

Example: To overload binary operator(+) to concatenate two strings:


#include<iostream>
#include<string.h>
using namespace std;

class opload
{
public:
char str[20];
public:
void input()
{
cout<<"\n Enter String";
cin>>str;
}
void output()
{
cout<<str;
}
opload operator +(opload x) //Concatenating String
{
opload s;
strcat(str,x.str);
strcpy(s.str,str);
return s;
}
[TYPE HERE] 26 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI
};
int main()
{
opload str1, str2, str3;

str1.input();
str2.input();
str3=str1+str2; //String is concatenated. Overloaded '+' operator
cout<<"\n\n Concatenated String is : ";
str3.output();
return 0;
}

Q7. What is template class and template function? Write a function template for
sorting an array.

Ans: A template is a blueprint or formula for creating a generic class or a function.


Templates in C++ programming allows function or class to work on more than one data type
at once without writing different codes for different data types. Templates are often used in
larger programs for the purpose of code reusability and flexibility of program. The concept of
templates can be used in two different ways:

1) Function Templates
2) Class Templates

Function Templates
A function templates work in similar manner as function but with one key difference. A single
function template can work on different types at once but, different functions are needed to
perform identical task on different data types. If you need to perform identical operations on
two or more types of data then, you can use function overloading. But better approach would
be to use function templates because you can perform this task by writing less code and code
is easier to maintain.

How to define function template?


A function template starts with keyword template followed by template parameter/s inside <
> which is followed by function declaration.

Syntax:

template <class T>


<ret-type> <func-name>(parameter list)
{
// body of function
}

[TYPE HERE] 27 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI


Example of Function Template

/* C++ program to display larger number among two numbers using function templates. */
/* If two characters are passed to function template, character with larger ASCII value is
displayed. */

#include <iostream.h>
template <class T>
T Large(T n1, T n2)
{
return (n1>n2) ? n1:n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
cout<<"Enter two integers: ";
cin>>i1>>i2;
cout<<Large(i1, i2)<<" is larger.";
cout<<"\n\nEnter two floating-point numbers: ";
cin>>f1>>f2;
cout<<Large(f1, f2)<<" is larger.";
cout<<"\n\nEnter two characters: ";
cin>>c1>>c2;
cout<<Large(c1, c2)<<" has larger ASCII value.";
return 0;
}

Class Templates
Just as we can define function templates, we can also define class templates. The general
form of a generic class declaration is shown here:

template <class type>


class class-name
{
body of function
.
.
};

[TYPE HERE] 28 | P A G E PREPARED BY: VIPIN KUMAR SARAOGI

You might also like