Oop QB Ans
Oop QB Ans
Overloading operators are only for classes. We cannot overload the operator for built-in
data types.
Some operators like ::, .?, sizeof, and typeid cannot be overloaded.
Some operators can only be overloaded as member functions .Operators like =, (), [],
and -> must be overloaded as member functions.
• Binary operators overloaded through a member function take one explicit argument and
those which are overloaded through a friend function take two explicit arguments.
Operator Overloading is a feature in C++ that allows you to redefine the meaning of an
existing operator
T Template/Library Use Allows use with STL containers (e.g., sort, set).
A friend function is a special function that is not a member of a class, but it is granted access
to the private and protected members of the class.
You declare a function as a friend using the friend keyword inside the class. It is commonly
used when two or more classes need to share private data with a common function.
Syntax:
class ClassName {
};
#include <iostream>
using namespace std;
class Box {
private:
int length;
public:
Box(int l) {
length = l;
};
void displayLength(Box b) {
cout << "Length of the box is: " << b.length << endl;
int main() {
Box box1(15);
displayLength(box1);
return 0;
#include <iostream>
class Student {
private:
int roll;
string name;
public:
Student(int r, string n) {
roll = r;
name = n;
void display() {
cout << "Roll No: " << roll << ", Name: " << name << endl;
};
int main() {
// Displaying students
s1.display();
s2.display();
s3.display();
if (s1 == s2)
cout << "s1 and s2 are equal." << endl;
else
if (s1 == s3)
else
return 0;
#include<iostream>
class Counter {
int value;
public:
Counter() : value(0) {}
void display() { cout << "Value: " << value << endl; }
void operator++() {
++value;
};
int main() {
Counter c;
++c;
c.display();
return 0;
}
Write a program in C++ to use scope resolution operator.
#include <iostream>
class Demo {
public:
void setValues(int x) {
void showValues() {
cout << "Global x = " << ::x << endl; // Using scope resolution to access global x
};
int main() {
Demo d;
d.setValues(20);
d.showValues();
return 0;
Implement a C++ program for overloading + binary operator as a class member function to
perform addition of two complex numbers
#include <iostream>
class Complex {
public:
// Display function
cout << real << " + " << imag << "i" << endl;
};
int main() {
c3.display();
return 0;
What is a friend function? What are the merits and demerits of using the friend function?
Friend Function - A friend function is a special function that is not a member of a class, but
it is granted access to the private and protected members of the class.
You declare a function as a friend using the friend keyword inside the class. It is commonly
used when two or more classes need to share private data with a common function.
. The function is defined anywhere in the program like a normal function.
1. While defining the friend function, there is no need to use the scope resolution
operator as friend keyword.
2. The friend can be defined anywhere in the program similar to normal function.
3. It can be invoked like a normal function without the help of any object.
1. The friend function is declared in the class but it, not a member function of the class.
To access the private data members of class it is necessary to create objects.
2. When a function is friend of more than one class then forward declaration of class is
needed
operators.
#include <iostream>
class Complex {
private:
public:
// Constructor
};
out << c.real << " + " << c.imag << "i";
return out;
return in;
int main() {
Complex c;
return 0;
#include<iostream>
class Counter {
int value;
public:
Counter(int v) : value(v) {}
void operator--() {
--value;
void display() {
};
int main() {
Counter c(5);
--c;
c.display();
return 0;
#include<iostream>
class Complex {
public:
void display() {
cout << real << " - " << imag << "i" << endl;
};
Complex operator-(Complex c1, Complex c2) {
int main() {
c3 = c1 - c2;
c3.display();
return 0;
Unit 4
In C++, when a class is inherited using the protected access specifier, it means:
All public and protected members of the base class become protected in the derived
class.
They are not accessible outside the derived class (i.e., from main or other classes).
This is useful when you want to give limited access to base class features inside
derived classes, but hide them from external users.
#include<iostream>
class Base {
public:
void greet() {
};
public:
void callBase() {
};
int main() {
Derived d;
d.callBase(); // ✅ Allowed
return 0;
🔹 Types of Inheritance:
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
A virtual base class is used in multiple inheritance to prevent duplicate copies of a base
class when it's inherited by multiple derived classes.
Virtual Function
A virtual function is a member function in the base class that you expect to be overridden
in derived classes. It enables runtime polymorphism.
#include<iostream>
class Base {
public:
};
public:
};
int main() {
Base* ptr;
Derived d;
ptr = &d;
return 0;
Inheritance in C++ is a feature that allows a class (derived class) to acquire the properties
and behaviors (members) of another class (base class).
Types of Inheritance:
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
#include<iostream>
class A {
public:
void show() {
};
class B {
public:
void show() {
};
};
int main() {
C obj;
return 0;
Problem Solution
int main() {
C obj;
return 0;
Discuss the role of access specifiers in inheritance and show their visibility
Access specifiers (public, protected, and private) control the visibility and accessibility of
class members after inheritance.
They affect:
private ✅ Yes ❌ No ❌ No
#include<iostream>
class Base {
public:
int pub = 1;
protected:
int prot = 2;
private:
int priv = 3;
};
public:
void show() {
};
public:
void show() {
}
};
public:
void show() {
};
int main() {
PublicDerived p1;
p1.show();
return 0;
Syntax:
You can inherit from multiple base classes, each using the protected keyword.
🔍 Example:
#include<iostream>
class A {
public:
void showA() {
cout << "Base A\n";
};
class B {
public:
void showB() {
};
public:
void show() {
};
int main() {
C obj;
obj.show(); // ✅ OK
return 0;
#include<iostream>
public:
};
public:
void sound() {
};
int main() {
Dog d;
d.sound();
return 0;
Function Overloading
Function overloading means having multiple functions with the same name but
different parameter lists in the same class.
It is an example of compile-time polymorphism.
Overloaded functions must differ by number or type of parameters (not just return
type).
Improves code readability by using same function name for similar operations.
Return type can be same or different.
Achieved within the same scope (usually in the same class).
Example:
#include<iostream>
public:
void show(int a) {
void show(double b) {
void show(string s) {
};
int main() {
Print p;
p.show(10);
p.show(3.14);
p.show("Hello");
return 0;
Function Overriding
Function overriding occurs when a derived class provides its own version of a base class’s
virtual function.
Example:
#include<iostream>
class Animal {
public:
};
public:
};
int main() {
Animal* a;
Dog d;
a = &d;
return 0;
Unit 5
Explain any five differences between function overloading vs function templates
Definition Multiple functions with the same name Single function definition that works
but different parameter types with any data type
Compile Time Decision made at compile time Template expanded at compile time
Flexibility Limited to types you define Works for any type automatically
Demonstrate a program to detect and catch divide by zero division error problem in C++
#include<iostream>
int main() {
int a, b;
try {
if (b == 0)
return 0;
Write a C++ program using function template to find the product of two integer or
floating-pointtype of data
#include<iostream>
T multiply(T a, T b) {
return a * b;
int main() {
cout << "Product of 2.5 and 4.2: " << multiply(2.5, 4.2) << endl;
return 0;
A class template can take more than one type using multiple template parameters. This
allows you to create generic classes that work with multiple data types.
#include<iostream>
class Pair {
T1 first;
T2 second;
public:
void setValues(T1 a, T2 b) {
first = a;
second = b;
void showValues() {
cout << "First: " << first << ", Second: " << second << endl;
}
};
int main() {
p1.setValues(10, 5.5);
p1.showValues();
p2.setValues("Age", 25);
p2.showValues();
return 0;
🔹 Syntax:
namespace name {
// declarations
Example:
#include<iostream>
namespace A {
void display() {
namespace B {
void display() {
int main() {
return 0;
In C++, a stream is an object used to perform input and output (I/O) operations.
Think of a stream as a flow of data between your program and a device (like keyboard,
screen, or file).
C++ provides different streams for input and output, mainly divided into:
int x;
#include<fstream>
ifstream fin("data.txt");
#include<fstream>
ofstream fout("data.txt");
#include<fstream>
Unit 6
In C++, file mode determines how a file is opened and how data is read from or written to
the file. File modes are defined using constants in the ios (input/output stream) class.
File modes are used with file streams like ifstream, ofstream, and fstream to specify whether
a file is to be opened for:
reading,
writing,
appending,
ios::ate – Move the file pointer to the end of file upon opening, but allows
reading/writing anywhere in the file.
ios::trunc – Truncates the file to zero length if it already exists (used with ios::out).
✅ Combining Modes
This line opens the file for both reading and writing.
Mode Purpose
3. Read/write failure
1. fail()
2. eof()
3. bad()
4. good()
5. is_open()
Functio Purpose
n
What is the difference between opening a file with constructor function and opening a file
with open () function
Definition Time File is opened when the object File is opened explicitly later using the
is created (instantiated). open() function.
Flexibility Less flexible — one file per More flexible — same object can open
object at a time. multiple files.
Use Case Best when file name is known Ideal when file name is dynamic (runtime
at compile time. input).
Multiple Files with Not possible; new object Possible — close one file and open another
One Object needed for each file. using same object.
Clarity / Brevity Shorter, cleaner syntax. Slightly more code, but allows more
control.
File Opening Mode Can use modes like ios::app, Can use the same modes when calling
Support ios::binary, etc. open().
Error Checking Slightly harder to handle Easier to check file open status (e.g., if (!
errors. file) check).
Real-life Example Writing a log to a known file Choosing a file based on user input (cin >>
(log.txt) filename;)
Changing File Mid- Not possible with constructor. Possible — close and open different files
Program with same object.
Write a program using the open ( ), eof ( ) & getline ( ) functions to open
#include<iostream>
#include<fstream>
#include<string>
int main() {
ifstream file;
string line;
file.open("sample.txt");
if (!file.is_open()) {
return 1;
while (!file.eof()) {
getline(file, line);
if (file.good()) {
return 0;
Explain file functions for text file and binary file operations
These handle raw byte data and are used for non-text data (e.g., images, structures, etc.).
Function Purpose
Function Purpose
Syntax:
file.seekg(offset, direction);
Example:
Syntax:
file.seekp(offset, direction);
Example:
Example:
Example:
🧠 Directions Used
Summary Table
Function Purpose Used For
seekg() Move get pointer Reading
seekp() Move put pointer Writing
tellg() Get get pointer pos Reading
tellp() Get put pointer pos Writing
#include<iostream>
#include<fstream>
int main() {
char ch;
while (cin.get(ch)) {
if (ch == '$')
break;
return 0;
Demonstrate a C++ program to create and write to .txt file with open() function to write
string “welcome”
#include<iostream>
#include<fstream>
int main() {
ofstream fout;
fout.open("welcome.txt");
fout.close();
return 0;