0% found this document useful (0 votes)
20 views

Chapter 5 Operator Overloading

Uploaded by

basur00basur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Chapter 5 Operator Overloading

Uploaded by

basur00basur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

College of Business, Science &Technology (CBST), Mymensingh

Department of Computer Science and Engineering

Object Oriented Programming (OOP)

Operator Overloading

Prepared by
Md. Masum Billah
Lecturer, Dept. of CSE, CBST
Mobile: 01793200796
There are 2 types of overloading in C++ :
1. Function overloading
2. Operator overloading

Operator overloading is one of the best features of C++. By overloading the operators, we can give
additional meaning to the operators like + - * / = . , etc., which by default are supposed to work only on
standard data types like int, float, char, void etc. It is an essential concept in C++. It’s a type of
polymorphism in which an operator is overloaded to give it the user-defined meaning.

Q. What are operators?


An operator is a symbol that tells the compiler to perform specific mathematical, logical calculations or
some other special operations.

Q 1. What is operator overloading?


Operator overloading is a feature in many programming languages that allows us to define and customize
the behavior of operators (such as +, -, *, /, ==, <, etc.) for user-defined classes or data types. In other
words, it lets us provide a specific meaning or action for these operators when they are used with objects of
our custom classes.

Example: (Not needed)


#include <iostream>
using namespace std;

class Sum {
private:
int red, green;

public:
Sum(int r = 0, int g = 0)
{
red = r;
green = g;
}
// This (Operator Function) is automatically called when '+' is used between two Sum objects

Sum operator+(Sum const& obj)


{
Sum tmp;
tmp.red = red + obj.red;
tmp.green = green + obj.green;
return tmp;
}

void print() { cout << red << " " << green << '\n'; }
};

int main()
{
Sum s1(10, 5), s2(2, 4);
Sum s3 = s1 + s2;
s3.print();
}
Output: 12 9

Q 2. What is operator function?

An operator function is a special member function of a class that allows you to redefine the behavior of
an operator (such as +, -, ==, etc.) for objects of that class. This is known as operator overloading. By
overloading operators, we can make operators work with objects of user-defined types, much like they do
with built-in types.

Operator Function Syntax:

return_type operator symbol (parameter_list)


{

Q 3. Describe the syntax of an operator function?


Syntax of operator function is given below:

class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};

Here:

1. returnType- is the return type of the function.


2. operator- is a keyword.
3. symbol- is the operator we want to overload. Like: +, <, -, ++, etc.
4. arguments- is the arguments passed to the function.

Q 4. When is a friend function compulsory? Give example.

A friend function in C++ is necessary when a non-member function needs access to the private and
protected members of a class.

A friend function is required when:

1. We need to perform operations that involve accessing private or protected members of a class from
a function that is not a member of that class.

2. We don't want to change the encapsulation by making the members public, but still need an
external function to access the internals of the class.
Example: We have a class Rectangle that stores the dimensions of a rectangle, we want to write a separate
function calculateArea() to calculate the area without making it a class member function.

#include <iostream>
using namespace std;

class Rectangle {
private:
int width;
int height;

public:
Rectangle(int w, int h) : width(w), height(h) {}

friend int calculateArea(Rectangle rect);


};

int calculateArea(Rectangle rect) {


return rect.width * rect.height;
}

int main() {
Rectangle rect(5, 3);
cout << "Area: " << calculateArea(rect) << endl; // Output: Area: 15
return 0;
}

Q5. A friend function cannot be used to overload the “=” operator. Explain why?
A friend function is a non-member function of the class to which it has been defined as friend. Therefore it
just uses the functionality (functions and data) of the class. So it does not consist the implementation for
that class. That’s why it cannot be used to overload the assignment operator.

When we are overloading = operator using friend function, two = operations will exists:

1) compiler is providing = operator

2) programmer is providing(overloading) = operator by friend function.

Then simply ambiguity will be created and compiler will gives error. Its compilation error.
Q6. Difference between member operator function & friend operator function?

Member Operator Function Friend Operator Function


A member operator function is a member function A friend operator function is not a member of the
of a class that is used to overload an operator. class but is declared as a friend within the class.

It has access to the private and protected members It is not a member function, so it doesn't have
of the class for which it is a member. access to the private members of the class by
default.

It is invoked using an object of the class on which It is invoked directly without the help of object.
the operator is being applied.

It is defined within the class definition. It can be defined outside the class definition.

It can be used to provide more natural and intuitive It is used when we need to overload an operator
operator overloading for member access and involving two different classes, and try to access
modification. the private members of both classes.
It is declared with ‘operator’ keyword in the class It is declared using the ‘friend’ keyword in the class
declaration. declaration.

Q7. Describe the rules for operator overloading.


There are some rules for the operator overloading. These rules are like below-

1. Only built-in operators can be overloaded. If some operators are not present in C++, we cannot overload
them.
2. The number of operands on which they operate, it cannot be changed.
3. The precedence of the operators remains same.
4. The overloaded operator cannot hold the default parameters except function call operator “()”.
5. We cannot overload operators for built-in data types. At least one user defined data types must be there.
6. The assignment “=”, subscript “[]”, function call “()” and arrow operator “->” these operators must be
defined as member functions, not the friend functions.
7. Some operators like assignment “=”, address “&” and comma “,” are by default overloaded.

Q12. Which operator cannot be overloaded in C++ and why?


In C++, the following operators cannot be overloaded:

Scope Resolution Operator (::): The scope resolution operator is used to define the scope of functions,
variables, or classes. It cannot be overloaded because it's an essential part of how C++ manages
namespaces and class member access.

Member Access Operator (.): The member access operator is used to access members of an object
directly. It cannot be overloaded because it's a fundamental part of C++ syntax for accessing class
members.

Conditional Operator (?:): The conditional operator, also known as the ternary operator, is used for
conditional expressions. It cannot be overloaded because its behavior is well-defined and fundamental to
the language's syntax.
sizeof Operator: The sizeof operator is used to determine the size of an object or data type in bytes. It
cannot be overloaded because it's a compile-time operator that doesn't involve runtime behavior.

typeid Operator: The typeid operator is used for obtaining information about the type of an expression. It
cannot be overloaded because it's a part of the C++ type identification mechanism.

Function Call Operator (): While we can overload the function call operator for user-defined types
(classes), we cannot overload it for built-in types. This is because function call syntax is a fundamental
aspect of C++ function invocation.

Q13. Explain function overloading and operator overloading with example.

Function overloading allows you to create multiple functions with the same name but different parameter
types or numbers of parameters. This enables you to perform different operations using the same function
name, improving code readability.

Example:
#include <iostream>
using namespace std;

// Function to add two integers


int add(int a, int b) {
return a + b;
}

// Function to add two floats


float add(float a, float b) {
return a + b;
}

int main() {
cout << "Integer Sum: " << add(2, 3) << endl; // Calls add(int, int)
cout << "Float Sum: " << add(2.5f, 3.5f) << endl; // Calls add(float, float)
return 0;
}

Operator overloading allows you to redefine how operators (like +, -, *, etc.) work with user-defined
types (like classes). This makes it possible to use operators with class objects in a natural way.

Example:

#include <iostream>
using namespace std;

class Number {
public:
int value;

// Constructor
Number(int v) : value(v) {}
// Overloading the + operator
Number operator+(const Number& n) {
return Number(value + n.value);
}
};

int main() {
Number n1(5); // Number with value 5
Number n2(10); // Number with value 10
Number n3 = n1 + n2; // Adds n1 and n2

cout << "Number 1: " << n1.value << endl; // Output: 5


cout << "Number 2: " << n2.value << endl; // Output: 10
cout << "Number 3 (Sum): " << n3.value << endl; // Output: 15

return 0;
}

Q14. What are the ambiguous situation arises in case of function overloading?

1. Same Number of Arguments: When two functions have the same number of arguments but different
types, and the arguments can implicitly convert to either type, the compiler gets confused.

2. Similar Type Parameters: When functions take parameters of similar types, and the arguments can
match multiple overloads.

3. Default Arguments: If you have functions with default arguments, this can also lead to ambiguity.

Example:

#include <iostream>
using namespace std;

void func(int a, double b) {


cout << "Function with int and double" << endl;
}

void func(double a, int b) {


cout << "Function with double and int" << endl;
}

int main() {
func(5, 3); // Ambiguous: both int and double can be used
return 0;
}
Q8. Explain the multiple meaning of the operator “<<” and “>>” in C++.
These operators have multiple meanings depending on the context in which they are used-

1. Bitwise Operator:

left shift operator "<<" shifts the bits of a binary number to the left by a specified number of positions.

right shift operator ">>" shifts the bits of a binary number to the right by a specified number of positions.

Syntax: value << num_bits // for left shift

Syntax: value >> num_bits // for right shift

Example: (for less mark skip this)


int x = 5; // Binary: 0101
int Lshifted = x << 2; // Binary: 010100 (20 in decimal)

int y = 16; // Binary: 10000


int Rshifted = y >> 2; // Binary: 00100 (4 in decimal)

2. Stream Insertion (<<) and Extraction (>>) Operators:


In the context of input/output operations, the "<<" and ">>" operators are used for stream insertion and
extraction, respectively. These operators are used to interact with input/output streams like cin and cout.

The "<<" operator (stream insertion)


The ">>" operator (stream extraction)

Q9. Write a program that overloads the “+” operator using an operator “+ ()”
function.
Answer: Example of Q1

Q10. Write a C++ program that to overload ‘+’, ‘-’, ‘/’ and ‘*’ operators to add,
subtract, divide and multiply two float type object.
#include <iostream>
using namespace std;

class FloatArithmetic {
float value;

public:
// Constructor
FloatArithmetic(float v) { value= v; }

// Overloading operators
FloatArithmetic operator+(const FloatArithmetic& obj) {
return FloatArithmetic(value + obj.value);
}
FloatArithmetic operator-(const FloatArithmetic& obj) {
return FloatArithmetic(value - obj.value);
}

FloatArithmetic operator*(const FloatArithmetic& obj) {


return FloatArithmetic(value * obj.value);
}

FloatArithmetic operator/(const FloatArithmetic& obj) {


if (obj.value) return FloatArithmetic(value / obj.value);
cout << "Error: Division by zero!" << endl;

return FloatArithmetic(0);
}

void display() const {


cout << value;
}
};

int main() {
FloatArithmetic num1(10.0), num2(3.0);

cout << "Number 1: "; num1.display(); cout << endl;


cout << "Number 2: "; num2.display(); cout << endl;

cout << "Sum: "; (num1 + num2).display(); cout << endl;


cout << "Difference: "; (num1 - num2).display(); cout << endl;
cout << "Product: "; (num1 * num2).display(); cout << endl;
cout << "Quotient: "; (num1 / num2).display(); cout << endl;

return 0; }

Q11. We have classes X and Y, If A is an object of X and B is an object of Y. we want


to say A=B. What type of conversion routine should be used and where?
To allow the assignment of an object of class X (`A`) to an object of class Y (`B`), you should use a
conversion constructor or a conversion operator:

1. Conversion Constructor: Define a constructor in class Y that takes an object of class X as a parameter.
This allows the creation of an object of Y from an object of X.

2. Conversion Operator: Alternatively, define a conversion operator in class X that converts an object of
X to an object of Y.

In summary, either a conversion constructor in Y or a conversion operator in X should be used to enable


the assignment operation `A = B`.

You might also like