Pratik Bangar
Unit 3
Q.1
a) What is operator overloading? Why it is necessary to overload an operator?
Ans - Operator overloading is a feature in Object-Oriented Programming (OOP) (especially
in C++) that allows you to define or change the behavior of operators (like +, -, *, ==, etc.) for
user-defined data types (like classes or structures).
Operator overloading is necessary because:
1. Improves code readability:
You can write expressions like c1 + c2 (where c1 and c2 are complex numbers),
which looks clean and natural instead of using functions like add(c1, c2).
2. Supports object-oriented design:
It helps make user-defined types behave like built-in types.
3. Makes code intuitive:
Instead of using long method names, you can use simple operators for operations
on objects.
4. Essential for mathematical and logical operations:
Especially useful in programs involving vectors, matrices, complex numbers,
strings, etc.
Example –
1. #include <iostream>
2. using namespace std;
3. class Complex {
4. float real, imag;
5. public:
6. Complex(float r = 0, float i = 0) {
7. real = r;
8. imag = i;
9. }
10. Complex operator + (const Complex& obj) {
11. return Complex(real + [Link], imag + [Link]);
12. }
13. void display() {
14. cout << real << " + " << imag << "i" << endl;
15. }
16. };
17. int main() {
18. Complex c1(2.5, 3.5), c2(1.5, 2.5);
19. Complex c3 = c1 + c2;
20. [Link](); // Output: 4 + 6i
21. return 0;
22. }
b) Write a program in C++ to use scope resolution operator.
Ans – Code
1. #include <iostream>
2. using namespace std;
3. int num = 100;
4. class Demo {
5. public:
6. void show() {
7. int num = 50;
8. cout << "Local num: " << num << endl;
9. cout << "Global num using scope resolution operator: " << ::num << endl;
10. }
11. };
12. int main() {
13. Demo d;
14. [Link]();
15. return 0;
16. }
Output –
Local num: 50
Global num using scope resolution operator: 100
c) What is friend function? What are the merits & demerits of using the friend function?
Ans - A friend function is a function that is not a member of a class but has access to its
private and protected members.
You declare it using the keyword friend inside the class.
Syntax:
1. class MyClass {
2. int a;
3. public:
4. MyClass() { a = 10; }
5. friend void display(MyClass obj);
6. };
7. void display(MyClass obj) {
8. cout << "Value of a: " << obj.a;
9. }
>Merits of Friend Function:
1. Access to private/protected data:
It can access private members of a class without being a member of the class.
2. Helps in operator overloading:
Especially useful when overloading binary operators using non-member
functions.
3. Useful in two-class interaction:
A friend function can access members of multiple classes.
4. Better flexibility:
Sometimes, it is better to write a function outside a class rather than making it a
member.
>Demerits of Friend Function:
1. Breaks encapsulation:
Since it accesses private data, it violates the concept of data hiding.
2. Not in class scope:
Being a non-member function, it cannot be called using [Link] syntax.
3. Increases coupling:
The tight relationship between the friend function and class makes the code less
modular.
Q.2
a) What are the rules for over loading operators.
Ans - When overloading operators in C++, you must follow certain rules to maintain the
language's syntax, safety, and clarity.
1. Only Existing Operators Can Be Overloaded
You can overload operators like +, -, *, /, =, [], (), etc.
You cannot overload: :: (scope resolution), ., .*, sizeof, typeid, ?:, etc.
2. At Least One Operand Must Be a User-Defined Type
You can’t change how operators behave with only built-in types.
Allowed: obj + obj
Not Allowed: 5 + 10 (can't overload + for int)
3. Operator Overloading Must Preserve Arity
You cannot change the number of operands:
o Unary remains unary (-obj)
o Binary remains binary (obj1 + obj2)
4. Precedence and Associativity Cannot Be Changed
Overloading doesn’t change how operators are grouped or evaluated.
Example: a + b * c still does b * c first.
5. Some Operators Must Be Overloaded as Member Functions
Operators like =, [], (), and -> must be overloaded as member functions only.
6. Friend Functions Can Be Used for Overloading
Especially useful for binary operators where the left operand isn’t an object of the
class.
7. Syntax Should Be Intuitive
The overloaded operator should behave as expected, so code remains easy to read and
maintain.
b) Which operators can not be overloaded? Write steps to overload + operator so that it can add
two complex numbers.
Ans - Operators That Cannot Be Overloaded in C++:
1. :: → Scope resolution operator
2. . → Member access (dot) operator
3. .* → Pointer-to-member operator
4. ?: → Ternary (conditional) operator
5. sizeof → Size-of operator
6. typeid → Type information operator
7. alignof → Alignment operator
8. noexcept → Exception specifier
9. Type casting operators: const_cast, static_cast, reinterpret_cast, dynamic_cast
These are restricted by the C++ language and cannot be overloaded.
> Steps to Overload + Operator to Add Two Complex Numbers
Step 1: Define a Class -
Create a class named Complex with two private data members: real and imag.
Step 2: Define a Constructor -
Use a constructor to initialize complex numbers.
Step 3: Declare the Overloaded Operator Function -
Inside the class, declare the + operator function:
Complex operator + (const Complex&);
Step 4: Define the Operator Function -
Define the function to add real and imaginary parts of two complex numbers and return the
result.
Step 5: Create Objects and Use the + Operator -
In main(), create two complex number objects, add them using the + operator, and display the
result.
c) Write down program to overload unary operators? (Any three operators).
Ans - Unary minus -
Pre-increment ++
Logical NOT !
Program:
2. #include <iostream>
3. using namespace std;
4. class Num {
5. int x;
6. public:
7. Num(int a) { x = a; }
8. void operator - () { x = -x; }
9. void operator ++ () { ++x; }
10. bool operator ! () { return x == 0; }
11. void show() { cout << "x = " << x << endl; }
12. };
13. int main() {
14. Num n(5);
15. -n; // Unary minus
16. [Link]();
17. ++n; // Pre-increment
18. [Link]();
19. if (!n) // Logical NOT
20. cout << "x is zero\n";
21. else
22. cout << "x is not zero\n";
23. return 0;
24. }
Output -
x = -5
x = -4
x is not zero
Q1)
c) What is operator overloading? Write steps to overload << & >> operators.
Ans - Operator overloading allows you to define custom behavior for operators (like +, -,
<<, >>, etc.) when they are used with user-defined types (classes or structs). It makes objects
behave more like built-in types, improving code readability and usability.
Steps to Overload << (insertion) and >> (extraction) Operators
These operators are usually overloaded as friend functions because the left operand is a stream
object (ostream or istream), not the class object.
Step 1: Include <iostream> and declare your class.
1. #include <iostream>
2. using namespace std;
3. class MyClass {
4. int data;
5. public:
6. MyClass(int d = 0) : data(d) {}
Step 2: Declare << and >> operator overload functions as friends.
1. friend ostream& operator<<(ostream& out, const MyClass& obj);
2. friend istream& operator>>(istream& in, MyClass& obj);
3. };
Step 3: Define the << operator to output object data.
1. ostream& operator<<(ostream& out, const MyClass& obj) {
2. out << [Link];
3. return out;
4. }
Step 4: Define the >> operator to input object data
1. istream& operator>>(istream& in, MyClass& obj) {
2. in >> [Link];
3. return in;
4. }
> Complete Example Program
1. #include <iostream>
2. using namespace std;
3. class MyClass {
4. int data;
5. public:
6. MyClass(int d = 0) : data(d) {}
7. friend ostream& operator<<(ostream& out, const MyClass& obj);
8. friend istream& operator>>(istream& in, MyClass& obj);
9. };
10. ostream& operator<<(ostream& out, const MyClass& obj) {
11. out << [Link];
12. return out;
13. }
14. istream& operator>>(istream& in, MyClass& obj) {
15. in >> [Link];
16. return in;
17. }
18. int main() {
19. MyClass obj;
20. cout << "Enter a number: ";
21. cin >> obj; // uses overloaded >>
22. cout << "You entered: " << obj << endl; // uses overloaded <<
23. return 0;
24. }
a) What is operator overloading? Why it is necessary to overload an operator?
Ans - Operator overloading is a feature in C++ that allows you to define or redefine the
behavior of an operator (like +, -, *, =, <<, etc.) when it is used with user-defined types such
as classes or structures.
Instead of using functions like add(obj1, obj2), you can make your objects work with obj1 +
obj2 — making the code cleaner and more intuitive.
Why is it Necessary to Overload an Operator?
1. Improves Readability and Clean Code
Operator overloading allows natural expressions like c1 + c2 instead of [Link](c2),
which is easier to read and write.
2. Works Like Built-in Types
You can make objects behave like integers, floats, etc., supporting operations like
addition, comparison, assignment, and more.
3. Custom Behavior for Specific Needs
For example, adding two Complex numbers or comparing two Time objects.
4. Helps in Code Reusability and Maintainability
Common operators can be reused for custom logic, reducing repetitive code.
Example –
1. #include <iostream>
2. using namespace std;
3. class Complex {
4. int real;
5. public:
6. Complex(int r = 0) { real = r; }
7. Complex operator + (Complex obj) {
8. return Complex(real + [Link]);
9. }
10. void show() {
11. cout << "Value: " << real << endl;
12. }
13. };
14. int main() {
15. Complex c1(5), c2(10);
16. Complex c3 = c1 + c2;
17. [Link]();
18. return 0;
19. }
b) Write a program to demonstrate friend function in C++.
Ans – Code –
1. #include <iostream>
2. using namespace std;
3. class Box {
4. int length;
5. public:
6. Box(int l) { length = l; }
7. friend void showLength(Box b);
8. };
9. void showLength(Box b) {
10. cout << "Length: " << [Link] << endl;
11. }
12. int main() {
13. Box b1(10);
14. showLength(b1); // Calls friend function
15. return 0;
16. }
Output –
Length: 10
c) Give a programming example that overloads = = operator with its use.
Ans - overloading the == (equality) operator
Program to Overload == Operator.
1. #include <iostream>
2. using namespace std;
3. class Number {
4. int value;
5. public:
6. Number(int v = 0) {
7. value = v;
8. }
9. bool operator == (Number obj) {
10. return value == [Link];
11. }
12. };
13. int main() {
14. Number n1(10), n2(10), n3(5);
15. if (n1 == n2)
16. cout << "n1 is equal to n2" << endl;
17. else
18. cout << "n1 is not equal to n2" << endl;
19. if (n1 == n3)
20. cout << "n1 is equal to n3" << endl;
21. else
22. cout << "n1 is not equal to n3" << endl;
23. return 0;
24. }
Output:
n1 is equal to n2
n1 is not equal to n3
Q1)
b) Write down a C++ program to implement operator overloading for complex class.
Ans - C++ Program: Operator Overloading for Complex Class.
1. #include <iostream>
2. using namespace std;
3. class Complex {
4. float real, imag;
5. public:
6. Complex(float r = 0, float i = 0) {
7. real = r;
8. imag = i;
9. }
10. Complex operator + (const Complex& obj) {
11. return Complex(real + [Link], imag + [Link]);
12. }
13. void display() {
14. cout << real << " + " << imag << "i" << endl;
15. }
16. };
17. int main() {
18. Complex c1(2.5, 3.5);
19. Complex c2(1.5, 2.5);
20. Complex c3 = c1 + c2;
21. cout << "Sum of complex numbers: ";
22. [Link]();
23. return 0;
24. }
c) Explain Friend function with example.
Ans - A friend function is a function that is not a member of a class, but it is allowed to access
private and protected members of that class. To make a function a friend of a class, it must be
declared inside the class using the friend keyword.
>Why Use a Friend Function?
To allow an external function to access private data of a class.
Useful when two classes need to share data with a common function.
Helps in operator overloading where the left operand is not an object of the class.
Syntax:
1. class ClassName {
2. friend returnType functionName(arguments);
3. };
> Example:
1. #include <iostream>
2. using namespace std;
3. class Box {
4. private:
5. int length;
6. public:
7. Box(int l) {
8. length = l;
9. }
10. friend void displayLength(Box b);
11. };
12. void displayLength(Box b) {
13. cout << "Length = " << [Link] << endl;
14. }
15. int main() {
16. Box b1(10);
17. displayLength(b1);
18. return 0;
19. }
Output –
Length = 10
What is operator overloading? Write a program to overload Unary operator.
Q.2
a) What is operator overloading? Write a program to overload Unary operator.
Ans - Operator Overloading in C++ is a feature that allows you to redefine the behavior of operators
(like +, -, ++, etc.) for user-defined types such as classes. It lets objects of a class be used with operators
as if they were basic data types.
>C++ Program to Overload Unary - and ++ Operators.
1. #include <iostream>
2. using namespace std;
3. class Number {
4. int x;
5. public:
6. Number(int a) { x = a; }
7. void operator - () {
8. x = -x;
9. }
10. void operator ++ () {
11. ++x;
12. }
13. void display() {
14. cout << "Value: " << x << endl;
15. }
16. };
17. int main() {
18. Number n(5);
19. cout << "Original: ";
20. [Link]();
21. -n;
22. cout << "After - operator: ";
23. [Link]();
24. ++n;
25. cout << "After ++ operator: ";
26. [Link]();
27. return 0;
28. }
Output –
Original: Value: 5
After - operator: Value: -5
After ++ operator: Value: -4
b) Write down a C++ program for copy constructor for string class.
Ans - C++ Program: Copy Constructor for String Class.
1. #include <iostream>
2. #include <cstring>
3. using namespace std;
4. class MyString {
5. char *str;
6. public:
7. MyString(const char *s = "") {
8. str = new char[strlen(s) + 1];
9. strcpy(str, s);
10. }
11. MyString(const MyString &obj) {
12. str = new char[strlen([Link]) + 1];
13. strcpy(str, [Link]);
14. }
15. void display() {
16. cout << "String: " << str << endl;
17. }
18. ~MyString() {
19. delete[] str;
20. }
21. };
22. int main() {
23. MyString s1("Hello");
24. MyString s2 = s1;
25. cout << "Original: ";
26. [Link]();
27. cout << "Copied: ";
28. [Link]();
29. return 0;
30. }
Output –
Original: String: Hello
Copied: String: Hello
c) Differentiate friend function with normal function of the class.
Ans - Friend Function:
Normal (Member) Function:
1) A friend function is not a member of the class, but it is declared inside the class using
the friend keyword.
1)A normal function is a member of the class and is defined inside the class.
2) It can access private, protected, and public members of the class.
2) It can access all members (private, protected, public) of the class.
3) It is called like a normal function, not through an object (you usually pass objects as
arguments to it).
3) It is called using an object of the class (e.g., [Link]()).
4) It does not have a this pointer because it’s not tied to any particular object.
4) It has access to the this pointer, which points to the calling object.
5) Friend functions are useful when you want an external function to access the internal data
of the class, for example, in operator overloading where the left operand is not an object of
the class.
5) Member functions usually operate on the object’s own data and define its behavior.
6) Usually takes objects as arguments to operate on their data.
6) Takes fewer arguments because it works on the calling object's data directly.