Chapter 5 Operator Overloading
Chapter 5 Operator Overloading
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.
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
void print() { cout << red << " " << green << '\n'; }
};
int main()
{
Sum s1(10, 5), s2(2, 4);
Sum s3 = s1 + s2;
s3.print();
}
Output: 12 9
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.
class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};
Here:
A friend function in C++ is necessary when a non-member function needs access to the private and
protected members of a class.
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) {}
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:
Then simply ambiguity will be created and compiler will gives error. Its compilation error.
Q6. Difference between member operator function & friend operator function?
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.
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.
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.
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;
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
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;
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.
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);
}
return FloatArithmetic(0);
}
int main() {
FloatArithmetic num1(10.0), num2(3.0);
return 0; }
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.