C++ IMPORTANT QUESTIONS WITH ANSWERS
Unit 1: Operator Overloading and Friend Function
Q: What is operator overloading? Why is it necessary?
A: Operator overloading allows us to redefine the way operators work for user-defined types. It is
necessary to make operations on objects intuitive (e.g., using + for adding complex numbers).
Q: Rules for overloading operators.
A: 1. Only existing operators can be overloaded.
2. New operators cannot be created.
3. Overloaded operators must have at least one user-defined operand.
4. Precedence and associativity cannot be changed.
Q: Which operators cannot be overloaded?
A: Operators that cannot be overloaded include: :: (scope resolution), . (member access), .*
(pointer-to-member), sizeof, typeid, and ?: (ternary conditional).
Q: Program to overload binary + for complex numbers.
A: class Complex {
public:
int real, imag;
Complex(int r = 0, int i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
};
Q: Overload unary operators (any three).
A: class Sample {
int a;
public:
Sample(int x) : a(x) {}
Sample operator-() { return Sample(-a); }
Sample operator++() { a++; return *this; }
Sample operator--(int) { Sample temp = *this; a--; return temp; }
};
Q: Explain friend function with example.
A: Friend functions can access private members of a class. Example:
class A {
int x;
friend void show(A);
};
void show(A a) { cout << a.x; }
Q: Merits & demerits of friend functions.
A: Merits:
- Access private data.
- Useful for operator overloading.
Demerits:
- Breaks encapsulation.
- Tight coupling between classes.
Q: Overload << and >> operators with syntax.
A: friend ostream& operator<<(ostream &out, const ClassName &obj);
friend istream& operator>>(istream &in, ClassName &obj);
Q: Compare friend function with member function.
A: Friend: Defined outside class, no 'this' pointer, not inherited.
Member: Defined inside class, has 'this' pointer, supports inheritance.
Q: Program to overload == operator.
A: bool operator==(const ClassName& obj) {
return this->data == obj.data;
Q: Overload unary -- operator.
A: ClassName operator--() {
--data;
return *this;