OOP QUESTION With Solution
OOP QUESTION With Solution
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.
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.
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.
In the case of function overloading, the In the case of function overriding, the
signatures should be different. signatures should be the same.
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).
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;
}
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.
Ans: The Access Specifiers help to achieve Data Hiding in C++.Basically, access
specifiers are used to hide/show data from outside world.
Ans: Exceptions are runtime errors that a program encounters during its execution.
There are two types of exceptions:
1) Synchronous
2) Asynchronous
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.
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;
};
• 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.
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.
8 Marks Questions
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.
• 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.
Adding new data and functions is not easy. Adding new data and function is easy.
Ans:
#include <iostream.h>
using namespace std;
int main()
{
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.
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();
}
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.
#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();
}
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.
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;
}
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;
}
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);
...... .... ........
};
#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
};
void main()
{
clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "< <avg(obj); // calling friend function
getch();
}
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.
iso::ate File opened in append mode but read and write performed at the end
of the file.
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)
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();
}
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.
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.
Hierarchical inheritance
Many classes deriving from one class.
In this type of inheritance, multiple derived classes inherits from a single base class.
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
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.
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.
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
Stream-object.open(“filename”, mode)
ofstream outFile;
outFile.open("sample.txt");
ifstream inFile;
inFile.open("sample.txt");
Q6. What is operator overloading? How will you overload binary and unary
operators? Discuss both process with the help of programming implementation.
{
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;
}
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.
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.
Syntax:
/* 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: