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

operator overloading (1)

Operator overloading in C++ allows the redefinition of standard operators for user-defined types, enabling custom behavior for class objects. This involves creating special operator functions within the class to manipulate objects using operators like +, -, and ++. Additionally, certain operators, such as relational and stream operators, can also be overloaded to enhance functionality and usability of class instances.

Uploaded by

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

operator overloading (1)

Operator overloading in C++ allows the redefinition of standard operators for user-defined types, enabling custom behavior for class objects. This involves creating special operator functions within the class to manipulate objects using operators like +, -, and ++. Additionally, certain operators, such as relational and stream operators, can also be overloaded to enhance functionality and usability of class instances.

Uploaded by

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

Operator Overloading

Operator Overloading:

• C++ allows you to redefine how standard operators work when used
with class objects.
• In C++, we can change the way operators work for user-defined types
like objects and structures.
This is known as operator overloading
How to use an operator to manipulate class objects ?

For example:
• assume that a class named Date exists,
• and objects of the Date class hold the month, day, and year in member variables.
Suppose the Date class has a member function named add.
• The add member function adds a number of days to the date and adjusts the
member variables if the date goes to another month or year.

today.add(5); // adds five days to the date stored in the today object:
today += 5;

• This statement uses the standard += operator to add 5 to today. This


behavior does not happen automatically,
• However the += operator must be overloaded for this action to
occur.
Syntax for C++ Operator Overloading:

• To overload an operator, a special operator function is used.


• The function is defined inside the class or structure whose
objects/variables we want the overloaded operator to work with.
class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ... }
... .. ... };
Here,
returnType is the return type of the function.
Operator is a keyword.
Symbol is the operator we want to overload. Like: +, <, -, ++, etc.
arguments is the arguments passed to the function.
Operator Overloading in Unary Operators
++ Operator (Unary Operator) Overloading:

class Count {
private:
int value;
public:
Count() {
value=5; }

void operator ++ () // Overload ++ when used as prefix

{ ++value; }
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1;
// Call the "void operator ++ ()" function
++count1;
count1.display();
return 0;
}

• Here, when we use ++count1;


• the void operator ++ () is called. This increases the value attribute for the object
count1 by 1
++ Operator(postfix) Unary Operator Overloading:

To make ++ work as a postfix we use this syntax.

void operator ++ (int) {


// code
}

• Notice the int inside the parentheses.


• It's the syntax used for using unary operators as postfix;
• it's not a function parameter.
Return Value from Operator Function (++ Operator) Pre-fix:

// Overload ++ when used as prefix


Count operator ++ () {
Count temp;
// Here, value is the value attribute of the calling object
temp.value = ++value;
return temp;
}
The code for the postfix operator overloading will also similar.

Notice that we have created an object temp and returned its value to the operator
function. Also, notice the code temp.value = ++value;
The variable value belongs to the count1 object in main() because count1 is calling the
function, while temp.value belongs to the temp object.
int main() {
Count count1, result;
// Call the "Count operator ++ ()" function
result = ++count1;
result.display();

// Call the "Count operator ++ (int)" function


result = count1++;
result.display();

return 0;
}
Overloading the unary minus (-) operator.

#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12

public:
Distance() {
feet = 0;
inches = 0;}
Distance(int f, int i) {
feet = f;
inches = i; }
void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};

int main() {
Distance D1(11, 10), D2(-5, 11);

-D1; // apply negation


D1.displayDistance(); // display D1

-D2; // apply negation


D2.displayDistance(); // display D2

return 0;
}
Ovrerloading Logical NOT ( ! ):

• Logical NOT ( ! ): This operator returns true if the operand is false or


zero and vice-versa.
// C++ program for ! Operator overloading
#include <iostream>
using namespace std;
class A {
private:
int a;
public: // parameterized constructor
A(int n)
{ a = n; }
// This is automatically called when ! operator is used with object
bool operator!()
{
a = !a;
if (a)
return true;
else
return false;
}
};
// Driver Code
int main()
{
// Assigning by overloading constructor
A a1(7), a2(0);

// Overloading ! Operator
if (!a1) {
cout << "a1 value is zero" << endl;
}
else {
cout << "a1 value is non-zero" << endl;
}

if (!a2) {
cout << "a2 value is zero" << endl;
}
else {
cout << "a2 value is non-zero" << endl;
}
}
C++ Binary Operator Overloading :
// C++ program to overload the binary operator +
// This program adds two complex numbers
class Complex {
private: float real; float imag;
public:
// Constructor to initialize real and imag to 0
Complex() {
real=0,
imag=0; }
void input() {
cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
}
// Overload the + operator
Complex operator + (const Complex &obj)
{
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}

void output() {
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};
int main() {
Complex complex1, complex2, result;

cout << "Enter first complex number:\n";


complex1.input();

cout << "Enter second complex number:\n";


complex2.input();

// complex1 calls the operator function


// complex2 is passed as an argument to the function
result = complex1 + complex2;
result.output();

return 0;
}
Overload the binary operator +

Reference Example(FeetInches) Pg. No 838


Overloading Relational Operators :
• In addition to the assignment and math operators, relational
operators may be overloaded.
• This capability allows classes to be compared in statements that use
relational expressions such as:
if (distance1 < distance2)
{
... code ...
}
• Overloaded relational operators are implemented like other binary
operators.
• The only difference is that a relational operator function should
always return a true or false value.
class Distance {
private:
int feet;
int inches;
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
bool operator <(const Distance& d) {
if(feet < d.feet) {
return true;
}
if(feet == d.feet && inches < d.inches) {
return true;
}

return false;
}
// method to display distance
void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}
};

int main() {
Distance D1(11, 10), D2(5, 11);

if( D1 < D2 ) {
cout << "D1 is less than D2 " << endl;
} else {
cout << "D2 is less than D1 " << endl;
}

return 0;
}
Overloading the << and >> Operators :
• The stream insertion and stream extraction operators also can be
overloaded to perform input and output for user-defined types like an
object.
• Overloading these operators is done in a slightly different way, than
overloading other operators.
• cout is an object of ostream class and cin is an object of istream class
• These operators must be overloaded as a global function. And if we want to
allow them to access private data members of the class, we must make
them friend.
class Distance {
private:
int feet; int inches;
public:
Distance() {
feet = 0; inches = 0; }
Distance(int f, int i) {
feet = f; inches = i; }
friend ostream & operator<<( ostream &, const Distance & ) ;
friend istream &operator >> ( istream &, Distance & ) ; };
ostream &operator<<( ostream &output, const Distance &D )
{ output << "F : " << D.feet << " I : " << D.inches;
return output;
}
istream &operator>>( istream &input, Distance &D ) {
input >> D.feet >> D.inches;
return input;
}
int main() {
Distance D1(11, 10), D2(5, 11), D3;

cout << "Enter the value of object : " << endl;


cin >> D3;
cout << "First Distance : " << D1 << endl;
cout << "Second Distance :" << D2 << endl;
cout << "Third Distance :" << D3 << endl;

return 0;
}
class Complex
{ private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{ real = r; imag = i; }
friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c); };
ostream & operator << (ostream &out, const Complex &c) {
out << c.real;
out << "+i" << c.imag << endl;
return out; }
istream & operator >> (istream &in, Complex &c) {
cout << "Enter Real Part ";
in >> c.real;
cout << "Enter Imaginary Part ";
in >> c.imag;
return in; }
int main()
{
Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
Overloading the Subscript Operator
[]
The subscript operator is most frequently overloaded when a class has
an array as one of its data members.
class IntArray {
private:
int m_Array[100];
int m_length;
public:
IntArray(int length) {
if (length > 100)
m_length = length;
else
m_length = length;
for (int i = 0; i < m_length; i++)
m_Array[i] = i; }
void PrintArray() {
for (int i=0; i < m_length; i++)
cout << m_Array[i] << ", " ;
cout << endl << endl;
}
//overloaded indexing operator []

int& operator[](int index)


{
return m_Array[index];
}
};
int main()
{
// Create Array and Print Vales
IntArray b(10);
b.PrintArray();

//Using the indexing [] set some new values


cout << "The value at location 6: " << b[6] << endl;

//Set New Values and Print the Array


b[1] = 1000;
b[2] = 2000;
b[3] = 60000;
b.PrintArray();

return 0;
}
const int SIZE = 10;
class safearay {
private:
int arr[SIZE];
public:
safearay() {
register int i;
for(i = 0; i < SIZE; i++) {
arr[i] = i; } }
int &operator[](int i) {
if( i > SIZE ) {
cout << "Index out of bounds" <<endl;
// return first element.
return arr[0]; }
return arr[i]; }
};
int main() {
safearay A;

cout << "Value of A[2] : " << A[2] <<endl;


cout << "Value of A[5] : " << A[5]<<endl;
cout << "Value of A[12] : " << A[12]<<endl;

return 0;
}
Things to Remember in C++ Operator Overloading :

• Operator overloading cannot change the precedence and associativity of


operators. However, if we want to change the order of evaluation,
parentheses should be used.
• There are operators that cannot be overloaded in C++. They are:
1) :: (scope resolution)
2) . (member selection)
3) .* (member selection through pointer to function)
4) ?: (ternary operator)
5) Sizeof operator

You might also like