Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Overloading Operator in c++

The document explains operator overloading in C++, which allows custom data types to use operators like built-in types. It outlines the types of operators that can be overloaded, restrictions on operator overloading, and provides examples of overloading binary and unary operators. Additionally, it introduces the 'this pointer' concept, which allows member functions to access the invoking object's address.

Uploaded by

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

Overloading Operator in c++

The document explains operator overloading in C++, which allows custom data types to use operators like built-in types. It outlines the types of operators that can be overloaded, restrictions on operator overloading, and provides examples of overloading binary and unary operators. Additionally, it introduces the 'this pointer' concept, which allows member functions to access the invoking object's address.

Uploaded by

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

OPERATOR OVERLOADING IN C++

OPERATORS IN C++
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C++ is rich in built-in operators
and provide the following types of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
WHAT IS OPERATOR OVERLOADING?
 C++ has the feature to bridge-in the gap between the user-defined
data-type variables and built-in data-type variables, by allowing us
to work on both type of variables in a same way by the concept
of operator overloading.

 It provides a special meaning to the operators so that it could work in the


same way for both built-in and user defined datatype.

 For example, we could add two built-in data type int variables by just
using the + operator between these two int variables
(int a+ int b= int c)

 Similarly, C++ also allows us to use + operator on two objects of user-


defined data-type by using the concept of operator overloading
using member function or a non-member friend function
(ob3=ob1+ob2)
OPERATOR OVERLOADING
 We cannot change the....
 number of operands an operator expects
 precedence and associativity of operators
 or use default arguments with operators

 We should not change...


 the meaning of the operator (+ does not mean subtraction!)
 the nature of the operator (3+4 == 4+3)
 provide consistent definitions (if + is overloaded, then +=
should also be)
RESTRICTIONS ON OPERATOR OVERLOADING

Operators that can be overloaded


+ - * / % ^ & |
• C++ OPERATORS THAT CAN BE OVERLOADED
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]

• C++ OPERATORS THAT CANNOT BE


OVERLOADED
Operators that cannot be overloaded
. .* :: ?: sizeof
EXAMPLE
 To overload an operator, a special operator function is defined inside the
class as:
 Here, returnType is the return
class className
{ type of the function.
... .. ...
public  The returnType of the function is
returnType operator followed by operator keyword.
symbol (arguments)
{
 Symbol is the operator symbol you
... .. ...
} want to overload. Like: +, <, -, ++
... .. ...
};  You can pass arguments to the
operator function in similar way as
functions.
OVERLOADING BINARY OPERATOR
In binary operator overloading
function, there should be one
argument to be passed.

It is overloading of an operator


operating on two operands.
OVERLOADING BINARY OPERATOR(+)
#include <iostream> // Function to display the values
using namespace std;
class Example void display() const
{ {
private: cout << "Value 1: " << value1 << ", Value 2: "
int value1; //These hold integer values for each << value2 << endl;
object. }
int value2; };

public: int main()


// Function to set the values of the object {
void setValues(int v1, int v2) Example obj1, obj2, obj3;
{
value1 = v1; value2 = v2; // Setting values for the objects
} obj1.setValues(10, 15);
obj2.setValues(20, 25);
// Member function to overload the + operator
Example operator+(Example obj) // Adding two objects using the overloaded +
{ operator
// No reference used here
Example temp; obj3 = obj1 + obj2;
temp.value1 = value1 + obj.value1;
temp.value2 = value2 + obj.value2; // Display the result
return temp; obj3.display();
} return 0; }
DISCUSSION OF THE PREVIOUS PROGRAM
The + operator is overloaded for the Example class, allowing objects of this class to be
added together. Here's a breakdown of what's happening:

1.Private members value1 and value2: These hold integer values for each object.

2.Function setValues: Allows setting the values of value1 and value2 for each object.

3.Overloading + operator: The operator+ function takes another Example object as


input, adds its value1 and value2 to the corresponding values of the current object, and
returns a new Example object containing the result.

4.Display function: Prints the values of the object's value1 and value2.

In the main function:


•Two objects obj1 and obj2 are initialized with values.
•They are added together using the overloaded + operator, and the result is stored in obj3.
•The values of obj3 are displayed.

Output: Value 1: 30, Value 2: 40


OVERLOADING BINARY OPERATOR(+)
Class Number int main()
{ {
private: int value; // Private member variable to store Number num1(10), num2(20); // Create two
the integer value objects with initial values
public: // Constructor to initialize the value Number result = num1 + num2; // Use overloaded
Number (int v = 0) '+' operator to add the objects
{
value = v; // Display the results
} cout << "First Number: "; num1.display();
// Overload the '+' operator to add two Number cout << "Second Number: "; num2.display();
objects Number operator+(Number const &obj) cout << "Result of Addition: "; result.display();
{ return 0;
Number result; // Create a temporary object to store the }
result result.value = value + obj.value; // Add the values
of the two objects
return result; // Return the result object
}
// Function to display the value
void display()
{
Expected Output:
cout << "Value: " << value << endl; num1(10) and num2(20), here's the step-by-step result:
Given the values
1.num1.display() will output the value of num1, which is 10.
} 2.num2.display() will output the value of num2, which is 20.
}; 3.result.display() will output the sum of num1 and num2, which is 30.
OVERLOADING BINARY OPERATOR(+)
class complex { void main() {
int a, b; complex obj1, obj2, result, result1;
public:
void getvalue() { obj1.getvalue();
cout << "Enter the value of Complex Numbers obj2.getvalue();
a,b:";
cin >> a>>b; result = obj1 + obj2;
} // Overloading the + operator to add two complex result1 = obj1 - obj2;
numbers
complex operator+(complex ob) { cout << "Input Values:\n";
complex t; obj1.display();
t.a = a + ob.a; obj2.display();
t.b = b + ob.b;
return (t); cout << "Result:";
} result.display();
complex operator-(complex ob) result1.display();
{ }
complex t;
t.a = a - ob.a; Enter the value of Complex Numbers a, b: 4 5
t.b = b - ob.b; Enter the value of Complex Numbers a, b : 2 2
return (t); Input Values Result
} 4 + 5i 6+7i
void display() { 2 + 2i 2+3i
cout << a << "+" << b << "i" << "\n";
}
OVERLOADING + OPERATOR USING THIS POINTER
#include <iostream> {
using namespace std; // Create an object to return Distance
d3 and Perform addition of feet and
class Distance { inches
public: d3.feet = this->feet + d2.feet;
int feet, inch; // Member Object d3.inch = this->inch + d2.inch;
Distance() // No Parameter Constructor
{ return d3; // Return the resulting
this->feet = 0; object
this->inch = 0; }
} };
int main()
// Constructor to initialize the object's value {
// Parametrized Constructor Distance d1(8, 9); // first object
Distance(int f, int i) Distance d2(10, 2); // second object
{ Distance d3; // Declaring third object
this->feet = f; d3 = d1 + d2; // Use overloaded
this->inch = i; operator
} cout << "\nTotal Feet & Inches: " <<
// Overloading (+) operator to perform addition of two d3.feet << "'" << d3.inch;
distance object
return 0;
Distance operator+(Distance& d2) // Call by
}
reference
OUTPUT: Total Feet & Inches: 18'11
UNARY (-)OVERLOADING
#include<iostream> ABC ABC: : operator - ( )
using namespace std; {
ABC A1;
class ABC A1.a= - a;
{ return A1;
int a; };
public:
ABC(int x) int main( )
{ {
a=x; ABC Ob(5);
} Ob= -Ob;
ABC( ) { Ob. show ( );
} }
ABC operator –( );
void show( ) OUTPUT: -5
{
cout<<a<<“ ”<<b;
}
};
UNARY OPERATOR OVERLOADING
Class ABC ABC ABC: : operator ++ (int)
{ {
int x; x++;
public: return *this;
ABC(int i) };
{
x=i; int main( )
} {
void operator ++(); // prefix ABC O1(5), O2(6);
ABC operator ++(int); //postfix cout<< “Before increment:”<<endl;
void show( ) O1.show( );
{ O2.show( );
cout<<x<<endl; cout<<“ After increment:”<<endl;
} ++O1;
}; O1.show ( );
O2=O2++
void ABC : : operator ++ ( ) O2.show ( );
{ }
++x;
OUTPUT: Before increment: 5 6
}
After increment: 6 7
UNARY OPERATOR OVERLOADING EXAMPLE
#include <iostream> int main()
using namespace std; {
Test t;
class Test // this calls "function void
{ operator ++()" function
private: ++t;
int count; t.Display();
return 0;
public:
Test(): count(5){} OUTPUT: Count: 6
void operator ++()  In the above example, ++ operator
{ operates on object to increase the value
count = count+1; of data member count by 1.
}
void Display() {
cout<<"Count: "<<count; }
};
}
INTRODUCTION TO “THIS POINTER”
 Every object in C++ has access to its own address through an
important pointer called this pointer.

 The “this pointer” is an implicit parameter to all member


functions

 When a member function is called, it automatically passes an


implicit parameter which serves as a pointer to the invoking
object. That pointer is called “this pointer”

 For a class X, the type of this pointer is ‘X*’. Also, if a member


function of X is declared as const, then the type of this pointer
is ‘const X *’
EXAMPLE
*When local variable’s name is same as member’s name*

#include<iostream> int main()


using namespace std; {
Test obj;
/* local variable is same as a member's name */ int x = 20;
class Test obj.setX(x);
{ obj.print();
private: return 0;
int x; }
public:
void setX (int x) OUTPUT: x=20
{
// The 'this' pointer is used to retrieve the
object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
EXAMPLE (THIS POINTER)
#include<iostream>
using namespace std;
int main()
/* local variable is same as a member's name */ {
class Test Test obj;
{ int x = 20;
private: obj.setX(x);
int x; obj.print();
public: return 0;
void setX (int x) }
{
// The 'this' pointer is used to retrieve the OUTPUT: x=20
object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
EXAMPLE
 Overloaded operators are functions with special names: the keyword
"operator" followed by the symbol for the operator being defined. Like
any other function, an overloaded operator has a return type and a
parameter list.
Box operator+(const Box&);

Here the addition operator that can be used to add two Box objects and returns final Box
object.
Questions?????

You might also like