Operator Overloading
Operator Overloading
Chapter
Operator Overloading
Prepared by
Md. Masum Billah
Lecturer, Dept. of CSE, CBST
Mobile: 01793200796
Operator Overloading
There are 2 types of overloading in C++ :
1. Function overloading 2. Operator overloading
Chapter Idea: 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.
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:
#include <iostream>
using namespace std;
class Sum {
private:
int red, green;
public:
Sum(int r = 0, int g = 0)
{
red = r;
greed = g;
}
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}
Output: 12 9
Q2. what is operator function?
Operator functions in is a special member functions that is used for operator overloading. The only
differences are, that the name of an operator function is always the operator keyword followed by
the symbol of the operator, and operator functions are called when the corresponding operator is
used.
We define the function inside the class or structure whose objects/variables we want the overloaded
operator to work with.
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.
1. Accessing Private Members: If we want a non-member function to access the private members of a
class, we need to declare that function as a friend of the class. This is useful when we need to allow
external functions to manipulate or access internal data that is otherwise encapsulated. Example:
// C++ program to demonstrate the working of friend function
#include <iostream>
using namespace std;
class Distance {
private:
int meter=0;
public:
// friend function declaration
friend int addFive(Distance);
};
class ClassA;
class ClassB {
private:
int privateDataB=4;
public:
friend int operator+(const ClassA& a, const ClassB& b);
};
class ClassA {
private:
int privateDataA=5;
public:
friend int operator+(const ClassA& a, const ClassB& b);
};
int main() {
return 0;
}
In this example, the operator+ function is declared as a friend in both ClassA and ClassB so that it can access private members
from both classes.
Q5. A friend function cannot be used to overload the “=” operator. Explain why?
Assignment(=) operator is a special operator that will be provided by the constructor to the class
when programmer has not provided(overloaded) as member of the class.(like copy constructor).
When programmer is 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?
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.
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.
Q14. What are the ambiguous situation arises in case of function overloading?
When the compiler is unable to decide which function it should invoke first among the overloaded
functions, this situation is known as function overloading ambiguity. The compiler does not run the
program if it shows ambiguity error. Causes of Function Overloading ambiguity:
1. Type Conversion.
2. Function with default arguments.
3. Function with a pass by reference.
1. Type Conversion: The below example throws an error – “call of overloaded ‘function(double)’ is
ambiguous”. The function(3.4) will call the first function. The function(34) calls the second function
according to our prediction. But this is not what happens because in C++ all the floating-point
constants are treated as double not as a float. If we replace the float variable to a double variable, the
program will work fine. Therefore we call this a type conversion error from float to double. For
example:
#include<iostream>
using namespace std;
void function(float);
void function(int);
void function(float x)
{
cout << "Value of x is : " <<x<< endl;
}
void function(int y)
{
cout << "Value of y is : " <<y<< endl;
}
int main()
{
function(3.4);
function(34);
return 0;
}
2. Function with Default Arguments: The below example gives an error saying “call of overloaded
‘fun(int)’ is ambiguous”, this is because function(int y, int z=12) can be called in two ways.
a. By calling the function with one argument (and it will automatically take the value of z = 12)
b. By calling the function with two arguments.
When we call the function: function(12) we full fill the condition of both function(int) and function(int,
int) thus the compiler gets into an ambiguity shows an error.
Example:
#include<iostream>
using namespace std;
void function(int);
void function(int,int);
void function(int x)
{
cout << "Value of x is : " <<x<< endl;
}
void function(int y,int z=12)
{
cout << "Value of y is : " <<y<< endl;
cout << "Value of z is : " <<z<< endl;
}
int main()
{
function(12);
return 0;
}
3. Function with pass by: The below program gives an error saying “call of overloaded ‘fun(int&)’ is
ambiguous”. As we see the first function takes one integer argument and the second function takes a
reference parameter as an argument. In this case, the compiler is not able to understand which
function is needed by the user as there is no syntactical difference between the fun(int) and fun(int &)
thus it shots an error of ambiguity. Example:
#include <iostream>
using namespace std;
void function(int);
void function(int &);
void function(int a)
{
cout << "Value of a is : " <<a<< endl;
}
void function(int &b)
{
cout << "Value of b is : " <<b<< endl;
}
int main()
{
int x=10;
function(x);
return 0;
}
Q8. Explain the multiple meaning of the operator “<<” and “>>” in C++.
In C++, the operators "<<" and ">>" are commonly used for bit manipulation and input/output
operations. These operators have multiple meanings depending on the context in which they are
used-
Bitwise Left Shift (<<) and Right Shift (>>) Operator: The bitwise left shift operator "<<" shifts the
bits of a binary number to the left by a specified number of positions. And The bitwise right shift
operator ">>" shifts the bits of a binary number to the right by a specified number of positions. these
are used primarily for bit manipulation and is often used to perform multiplication or create bit
patterns.
Syntax: value << num_bits // for left shift
Example:
int x = 5; // Binary: 0101
int Lshifted = x << 2; // Binary: 010100 (20 in decimal)
The "<<" operator (stream insertion) is used to insert data into an output stream like cout.
The ">>" operator (stream extraction) is used to extract data from an input stream like cin.
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 the + operator
FloatArithmetic operator+(const FloatArithmetic& obj) {
return FloatArithmetic(value + obj.value);
}
void display() {
cout << value;
}
};
int main() {
FloatArithmetic num1(10.0);
FloatArithmetic num2(3.0);
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?
We have to use class type conversion. Class conversion can be achieved by conversion function which
is done by the use of operator overloading. The type-conversion function to be located in the source
class or in the destination class.