OOP question bank
solution
1) What is the purpose of input and output stream?
Ans- Input and Output (I/O) streams are fundamental components
of programming that enable communication between a program
and external devices or systems.
Purpose of Input Stream:
1. Read data from external sources (e.g., keyboard, files, network).
2. Provide data to a program for processing.
3. Allow user interaction (e.g., inputting values, commands).
Purpose of Output Stream:
1. Send data to external devices or systems (e.g., monitor, files).
2. Display results of program execution.
3. Communicate with users (e.g., displaying messages, prompts).
2) Write a C++ program to read and write a string from/to the file.
Ans-
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string fileName,content;
cout << "Enter file name: ";
cin>> fileName;
cout << "Enter content: ";
cin>>content;
ofstream outFile(fileName);
outFile << content << endl;
outFile.close();
// Read from file
ifstream inFile(fileName);
getline(inFile, content);
inFile.close();
cout << "Content from file: " << content << endl;
return 0;
}
3) What is pointer? write down the general syntax and
declaration.
Ans- A pointer is a variable that stores the memory address of
another variable. It "points to" the location in memory where the
variable is stored. Pointers are used to:
1. Store and manipulate memory addresses.
2. Dynamically allocate memory.
3. Pass variables by reference to functions.
4. Improve performance by reducing data copying.
Syntax:
type *pointer_name;
Declaration:
int *ptr;
ptr = &x;
*ptr = 20;
ptr++;
Example Code:
int main()
{
int x = 10;
int *ptr = &x;
printf("%d", *ptr);
*ptr = 20;
printf("%d", x);
return 0;
}
4) What is the need of virtual function explain with example.
Ans- A virtual function is a member function (method) of a base
class that can be overridden by a derived class. It allows for
polymorphism, where objects of different classes can be treated
as objects of a common base class.
Need for Virtual Functions:
1. Polymorphism: Virtual functions enable polymorphism, where
objects of different classes can be treated as objects of a common
base class.
2. Late Binding: Virtual functions facilitate late binding, where the
function to be called is determined at runtime, rather than
compile-time.
3. Inheritance: Virtual functions support inheritance, allowing
derived classes to specialize behavior.
Example:
#include <iostream>
#include<conio.h>
class Shape
{
public:
virtual void area ()
{
cout << "Calculating area of shape" <<endl;
}
};
class Circle: public Shape
{
private:
double radius;
public:
Circle (double r): radius(r) {}
void area () override
{
cout << "Circle area: " << 3.14 * radius * radius <<endl;
}
};
class Rectangle: public Shape
{
private:
double length, width;
public:
Rectangle (double l, double w): length(l), width(w) {}
void area () override
{
cout << "Rectangle area: " << length * width <<endl;
}
};
int main ()
{
Shape* shape = new Shape ();
Circle* circle = new Circle (5);
Rectangle* rectangle = new Rectangle (4, 6);
shape->area ();
circle->area ();
rectangle->area ();
Shape* shapePtr = circle;
shapePtr->area ();
shapePtr = rectangle;
shapePtr->area ();
return 0;
}
5) Write a program to find length of string using operator
overloading.
Ans-
#include <iostream>
#include <string>
using namespace std;
class String
{
public:
char str [100];
void operator>> (const char* s)
{
Strcpy (str, s);
}
void operator<< (const char*s)
{
Printf ("%s\n", str);
}
int operator! ( )
{
return strlen (str);
}
};
int main ()
{
String s;
char input [100];
printf ("Enter a string: ");
scanf ("%s", input);
s >> input;
printf ("You entered: ");
s << input;
printf ("Length: %d\n",!s);
return 0;
}
6) Explain pointer to array with example.
Ans- A pointer to an array is a pointer variable that points to the
memory address of an entire array.
Syntax:
dataType (*pointerName)[arraySize];
Example Program
#include <stdio.h>
int main ()
{
int arr[5] = {1, 2, 3, 4, 5};
int (*ptr)[5] = &arr;
printf("Array elements: ");
for (int i = 0; i < 5; i++)
{
printf("%d ", (*ptr)[i]);
}
return 0;
}
7) Difference between compile time and run time polymorphism.
Ans-
Sr.no Compile time Rum time
polymorphism polymorphism
1) In this polymorphism, an In this polymorphism,
object is bound to its selection of appropriate
function call at compile function is done at run time.
time.
2) Functions to be called are Function to be called is
known well before. unknown until appropriate
selection is made.
3) This does not require use This requires use of pointers
of pointers to objects. to object.
4) Function calls execution are Function calls execution are
Faster. Slower.
5) It is implemented with It is implemented with
operator overloading or virtual function.
function overloading.
8) Write a program to count number of lines in a file.
Ans-
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
string name;
string line;
int lines = 0;
cout << "Enter filename: ";
cin >> name;
ifstream file(name);
while (getline(file, line))
{
lines++;
}
cout << "Number of lines: " << lines <<endl;
return 0;
}
9) Define inheritance? Explain different types of inheritance with
example.
Ans- Inheritance is the process of acquiring the properties and
behaviours from parent class to child class.It supports the concept
of hierarchical classification. It also provides the idea of reusability.
Syntax:
class derived-class-name: visibility-mode base-class-name
{
------//
// members of derived class
-----//
};
Types of inheritance:
1) Single inheritance: In single inheritance, only one class is
derived from one base class.
Example:
#include<iostream.h>
#include<conio.h>
Class A
{
Public:
Void function ()
{
Cout<<”\n base class invoked”;
}
};
Class B
{
Void display ()
{
Cout<<” \n derived class invoked”;
}
};
Int main ()
{
A a;
B b;
a.function();
b.display ();
return 0;
}
2) Multiple inheritance: In multiple inheritance, derived class is
derived from more than one base classes.
Example:
#include<iostream.h>
#include<conio.h>
Class A
{
Public:
Void funA ()
{
Cout<<” \n base class1 invoked”;
}
};
Class B
{
Public:
Void funB ()
{
Cout<<” \n base class2 invoked”;
}
};
Class c: public A, public B
{
Public:
Void display ()
{
Cout<<” \n child class invoked”;
}
};
Int main ()
{
C c;
c.funA();
c.funB();
c.display ();
return 0;
}
3) Multilevel inheritance: In multilevel inheritance, a derived class
is derived from a derived class (intermediate base class) which in turn
derived from a single base class.
Example:
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name, gender;
int age;
public:
Person (string n, string g, int a)
{
name = n;
gender = g;
age = a;
}
void displayPerson()
{
cout << "Name: " << name <<endl;
cout << "Gender: " << gender <<endl;
cout << "Age: " << age <<endl;
}
};
class Employee : public Person
{
protected:
int emp_id;
string company;
double salary;
public:
Employee (string n, string g, int a, int id, string c, double s): Person (n,
g, a)
{
emp_id = id;
company = c;
salary = s;
}
void displayEmployee ()
{
displayPerson();
cout << "Employee ID: " << emp_id <<endl;
cout << "Company: " << company <<endl;
cout << "Salary: " << salary << endl;
}
};
class Programmer: public Employee
{
private:
int no_of_prog_lang_known;
public:
Programmer (string n,string g, int a, int id, string c, double s , int
lang): Employee(n, g, a, id, c, s)
{
no_of_prog_lang_known = lang;
}
void displayProgrammer ()
{
displayEmployee ();
cout << "No. of programming languages known: " <<
no_of_prog_lang_known <<endl;
}
};
int main ()
{
Programmer programmer ("John", "Male", 30, 101, "ABC Corp",
50000.0, 5);
programmer.displayProgrammer();
return 0;
}
4) Hybrid inheritance: Hybrid inheritance is a combination of
single, multiple, multilevel and hierarchical inheritance.
Example:
#include<iostream.h>
#include<conio.h>
Class vehicle
{
Public:
Void vehicle ()
{
Cout<<” \n this is vehicle “;
}
};
Class car: public vehical
{
Public:
Void car ()
{
Cout<<”\n This is a car”;
}
};
Class racing
{
Public:
Void racing ()
{
Cout<<”This is for racing”;
}
};
Class Ferrari : public car, public racing
{
Public:
{
Void Ferrari ()
{
cout<<” ferrari is racing car”;
}
};
Int main ()
{
Ferrari f;
Return 0;
}
5) Hierarchical inheritance: In hierarchical inheritance, more than
one derived classes are derived from single base class.
Example:
#include<iostream>
using namespace std;
class employee
{
protected:
int empid, empcode;
public:
void accept ()
{
cout<<"\n enter empid, empcode:";
cin>>empid>>empcode;
}
void display ()
{
cout << "emp_id= " << empid<<endl;
cout << "emp_code=" <<empcode<< endl;
}
};
class programmer: public employee
{
protected:
char skills [20];
public:
void gets ()
{
cout<<"enter skills:";
cin>>skills;
}
void show ()
{
cout << "skills=" << skills<<endl;
}
};
class manager: public employee
{
char dept [20];
public:
void gets1 ()
{
cout << "enter department:";
cin >> dept;
}
void puts ()
{
cout << "department =" << dept<<endl;
}
};
int main ()
{
programmer p;
manager m;
p.accept ();
p. gets ();
p. display ();
p. show ();
m.accept ();
m. gets1 ();
m.display ();
m. puts ();
return 0;
}
10)Write a program to swap integer and float number using function
overloading.
Ans-
#include<iostream.h>
#include<conio.h>
void swap (int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
cout<<"\n Integer values after swapping are:"<<a<<" "<<b;
}
void swap (float x,float y)
{
float temp1=x;
x=y;
y=temp1;
cout<<"\n Float values after swapping are:"<<x<<" "<<y;
}
void main ()
{
clrscr();
swap (10,20);
swap (10.15f,20.25f);
getch ();
}
11)List and Explain stream classes along with their function.
Ans-
Input Stream Classes:
1. istream: Base class for input streams.
- Functions: get (), getline(), ignore(), peek(), putback(), unget()
2. ifstream: Input file stream.
- Functions: open (), close (), eof (), fail (), good ()
3. istringstream: Input string stream.
- Functions: str (), clear (), seekg(), tellg()
Output Stream Classes:
1. ostream: Base class for output streams.
- Functions: put (), write (), flush (), endl()
2. ofstream: Output file stream.
- Functions: open (), close (), eof(), fail(), good()
3. ostringstream: Output string stream.
- Functions: str (), clear (), seekp(), tellp()
Input/Output Stream Classes:
1. iostream: Base class for input/output streams.
2. fstream: Input/output file stream.
- Functions: open(), close(), eof(), fail(), good()
3. stringstream: Input/output string stream.
- Functions: str(), clear(), seekg(), tellg(), seekp(), tellp()
12) Describe the purpose of protected access specifier.
Ans- The protected access specifier is used to define the accessibility
of a class member (variable or function) within a class hierarchy. The
protected access specifier is similar to the private access specifier in
the sence that it can't be accessed outside of its class unless with the
help of friend function.
Example:
class Base
{
protected:
int x;
public:
void setX (int val)
{
x = val;
}
};
class Derived: public Base {
public:
void printX()
{
cout << x << endl;
}
};
int main ()
{
Derived obj;
obj.setX(10);
obj.printX();
return 0;
}
13) Explain the concept of virtual base class with example.
Ans-
Virtual Base Class: An ancestor class is declared as virtual base class
which is used to avoid duplication of inherited members inside child
class due to multiple path of inheritance.
Consider the example of a hybrid inheritance:
The child class has two direct base classes, Parent1 and Parent2
which themselves have a common base class as Grandparent. The
child inherits the members of Grandparent via two separate paths.
All the public and protected members of Grandparent are inherited
into Child twice, first via Parent1 and again via Parent2. This leads to
duplicate sets of the inherited members of Grandparent inside Child
class. The duplication of inherited members can be avoided by
making the common base class as virtual base class while declaring
the direct or intermediate base classes.
Example:
#include<iostream.h>
class student
{
int rno;
public:
void getnumber()
{
cout<<"Enter Roll No:";
cin>>rno;
}
void putnumber()
{
cout<<"\n\n\t Roll No:"<<rno<<"\n";
}
};
class test: virtual public student
{
public:
int part1, part2;
void getmarks()
{
cout<<"Enter Marks\n";
cout<<"Part1:";
cin>>part1; cout<<"Part2:";
cin>>part2;
}
void putmarks()
{
cout<<"\t Marks Obtained\n";
cout<<"\n\t Part1:"<<part1;
cout<<"\n\tPart2:"<<part2;
}
};
class sports: public virtual student
{
public:
int score;
void getscore()
{
cout<<"Enter Sports Score:";
cin>>score;
}
void putscore()
{
cout<<"\n\t Sports Score is:"<<score;
}
};
class result: public test, public sports
{
int total;
public:
void display ()
{
total=part1+part2+score;
putnumber();
putmarks();
putscore();
cout<<"\n\t Total Score:"<<total;
}
};
void main ()
{
result obj;
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
getch();
}
14) Explain constructor in derived classes.
Ans- In C++, when a derived class object is created, the base class
constructor is called first, followed by the derived class constructor.
This ensures that the base class members are initialized before the
derived class members.
Types of Constructors in Derived Classes:
1. Default Constructor: No arguments are passed to the constructor.
2. Parameterized Constructor: Arguments are passed to the
constructor.
3. Copy Constructor: Creates a copy of an existing object.
Syntax:
class Derived: public Base
{
public:
Derived (): Base ()
{
// Explicit call to base constructor
// Derived class constructor code
}
Derived (int x): Base(x)
{
// Explicit call to base constructor
// Derived class constructor code
}
};
Example:
#include<iostream.h>
#include<conio.h>
class Person
{
public:
Person (string name)
{
cout << "Person constructor called" << endl;
}
};
class Employee: public Person
{
public:
Employee (string name, int id) : Person(name)
{
cout << "Employee constructor called" << endl;
}
};
int main ()
{
Clrscr ();
Employee e ("John", 123);
return 0;
}
15) Explain file modes used to perform file operations?
Ans- File modes determine the operations that can be performed on
a file when it's opened.
File Modes:
ios::in - Open for reading (input)
ios::out - Open for writing (output)
ios::ate - Open at end of file (output)
ios::trunc - Truncate file if exists (output)
ios::binary - Open in binary mode
ios::nocreate - Fail if file doesn't exist
ios::noreplace - Fail if file already exists
16) Write a program to copy Data from one file to another.
Ans-
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
string sourceFile, destinationFile;
cout << "Enter source file name: ";
cin >> sourceFile;
cout << "Enter destination file name: ";
cin >> destinationFile;
ifstream source(sourceFile);
ofstream destination(destinationFile);
if (! source ||! destination)
{
cerr << "Unable to open file";
return 1;
}
char ch;
while (source.get(ch))
{
destination.put(ch);
}
source.close();
destination.close();
cout << "File copied successfully";
return 0;
}