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

Operator Overloading

OOP 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)
6 views

Operator Overloading

OOP 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)

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.

Q. What are operators?


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

Q1. 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:

#include <iostream>
using namespace std;

class Sum {
private:
int red, green;

public:
Sum(int r = 0, int g = 0)
{
red = r;
greed = g;
}

// This(Operator Function) is automatically called when '+' is used with


// between two Complex objects
Complex operator+(Complex const& obj)
{
Sum res;
res.red = red + obj.red;
res.green = green + obj.green;
return res;
}
void print() { cout << red << “ ”<< green << '\n'; }
};

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.

Q3. 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.

Q4. When is a friend function compulsory? Give example.

A friend function is compulsory in following scenarios:

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);

};

// friend function definition


int addFive(Distance d) {

//accessing private members from the friend function


d.meter += 5;
return d.meter;
}
int main() {
Distance D;
cout <<"Distance: "<< addFive(D);
return 0;
}
2. Operator Overloading: When we want to define a non-member function (such as a binary operator)
that needs access to private members of more than one class, we need to declare it as a friend in
both classes.
Example: (May skip this example for less mark question)

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 operator+(const ClassA& a, const ClassB& b) {


return a.privateDataA + b.privateDataB;
}

int main() {

int sum = instanceA + instanceB; // Uses the friend operator+


std::cout <<"Sum: "<< sum << std::endl;

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:

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 A friend operator function is not a member of
function of a class that is used to overload an the class but is declared as a friend within the
operator. class.
It has access to the private and protected It is not a member function, so it doesn't have
members 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 Friend operator functions are used when we
intuitive operator overloading for member access need to overload an operator involving two
and modification. different classes, and we want to allow the
operator to access the private members of both
classes.
It is declared with ‘operator’ keyword in the class It is declared using the ‘friend’ keyword in the
declaration. class 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 operator overloading


Function overloading allows us to call it in Operator overloading allows operators to have
multiple ways. their extending meaning beyond its predefined
operational meaning.
We can overload the function with the same We can overload (define custom behaviour) for
name but with different parameters. operators such as ‘+’, ‘-‘, ‘()’, ‘[]’.
Function overloading means using a single name Operator overloading means adding extra
and giving more functionality to it. functionality for a certain operator.
When a function is overloaded, the same When an operator is overloaded, the operator
function name has different interpretations has different meanings, which depend on the
depending on its signature, which is the list of type of its operands.
argument types in the functions parameter list.

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

Syntax: value >> num_bits // for right shift

Example:
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)

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) 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);
}

// Overloading the - operator


FloatArithmetic operator-(const FloatArithmetic& obj) {
return FloatArithmetic(value - obj.value);
}

// Overloading the * operator


FloatArithmetic operator*(const FloatArithmetic& obj) {
return FloatArithmetic(value * obj.value);
}

// Overloading the / operator


FloatArithmetic operator/(const FloatArithmetic& obj) {
if (obj.value != 0) {
return FloatArithmetic(value / obj.value);
} else {
cout << "Error: Division by zero!" << endl;
return FloatArithmetic(0);
}
}

void display() {
cout << value;
}
};

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

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

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

FloatArithmetic sum = num1 + num2;

cout << "Sum: "<< sum.display() << endl;

FloatArithmetic difference = num1 - num2;


cout << "Difference: "<< difference.display() << endl;

FloatArithmetic product = num1 * num2;


cout << "Product: "<< product.display() << endl;

FloatArithmetic quotient = num1 / num2;


cout << "Quotient: "<< quotient.display() << 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?

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.

You might also like