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

Operator Overloading

The document provides multiple examples of operator overloading in C++, demonstrating how to overload various operators such as multiplication, prefix decrement, NOT, increment, and addition for different classes like Frac, OverLoad, NotOp, UnaryOverload, Time, and Complex. Each example includes code snippets, explanations, and outputs to illustrate the functionality of the overloaded operators. Additionally, it discusses the difference between copy constructors and assignment operators in the context of object initialization.

Uploaded by

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

Operator Overloading

The document provides multiple examples of operator overloading in C++, demonstrating how to overload various operators such as multiplication, prefix decrement, NOT, increment, and addition for different classes like Frac, OverLoad, NotOp, UnaryOverload, Time, and Complex. Each example includes code snippets, explanations, and outputs to illustrate the functionality of the overloaded operators. Additionally, it discusses the difference between copy constructors and assignment operators in the context of object initialization.

Uploaded by

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

Operator Overloading Examples

Example 1: Let us multiply two fractions using the overloading of the multiplication operator in C+
+.
// Multiplication of two fractions
#include <iostream>
using namespace std;

class Frac {
private:
int a;
int b;

public:
Frac() : a(0), b(0) {}

void in() {
cout << "Enter the numerator : ";
cin >> a;
cout<< "Enter the denominator : ";
cin >> b;
}

// Overload the * operator


Frac operator * (const Frac &obj) {
Frac temp;
temp.a = a * obj.a;
temp.b = b * obj.b;

return temp;
}

void out() {
cout<<"The fraction is "<< a<<"/ "<<b;
}
};

int main() {
Frac F1, F2, result;

cout << "Enter the first fraction:n";


F1.in();

cout << "Enter the second fraction:n";


F2.in();

// complex1 calls the operator function


// complex2 is passed as an argument to the function
result = F1 * F2;
result.out();

return 0;
}

OutPut
Enter the first fraction:
Enter the numerator : 2
Enter the denominator : 5
Enter the second fraction:
ENter the numerator: 12
Enter the denominator: 7
The fraction is 24/35

Explanation
This code demonstrates Operator overloading in C++ to multiply two fractions. The Frac class
defines a fraction with numerator a and denominator b and overloads the * operator to perform the
multiplication of fractions.

When executed, the program prompts the user to input two fractions, multiplies them using the
overloaded * operator, and prints the result. In the provided output, when the fractions 2/5 and 12/7
are multiplied, the result is correctly calculated as 24/35.

Example 2: A C++ program to overload a prefix decrement operator


#include <iostream>

class OverLoad {
private:
int a;
int b;

public:
void in() {
std::cout << "Enter the value of a: ";
std::cin >> a;
std::cout << "Enter the value of b: ";
std::cin >> b;
}

// Overload the prefix decrement operator


void operator--() {
a = --a;
b = --b;
}

void out() {
std::cout << "The decremented elements of the object are: " << std::endl
<< a << " and " << b;
}
};

int main() {
OverLoad obj;
obj.in();
--obj;
obj.out();

return 0;
}

Output
Enter the first number : 56
Enter the second number : 234
The decremented elements for the objects are: 55 and 223
Explanation
This code showcases the overloading of the prefix decrement operator in C++. The OverLoad class
represents two integer variables, a and b, and overloads the — operator to decrement both.

Upon execution, the program prompts the user to input two numbers, then decrements them using
the overloaded — Operator and displays the decremented values. In the provided output, 56 and
234 are decremented to 55 and 223 respectively.
Example 3: Overloading a NOT (!) operator
#include <iostream>
using namespace std;

class NotOp {
private:
int a;
bool b;

public:
NotOp() : a(0), b(true) {}

void in() {
cout << "Enter the first number : ";
cin >> a;
cout<< "Enter true or false : ";
cin >> b;
}

// Overloading the NOT (!) operator


void operator ! () {
a= !a;
b= !b;
}

void out() {
cout<<"Output: "<<endl<< a<<endl<<b;
}
};

int main() {
NotOp obj;
!obj;
obj.out();

return 0;
}

Output
1
0

Explanation
This code demonstrates the overloading of the NOT (!) Operator in C++. The NotOp class includes
an integer variable, a, and a boolean variable, b. It overloads the! The Operator will perform logical
negation on both variables.

Upon execution, the program prompts the user to input a number and a boolean value, then applies
the overloaded ! Operator and displays the negated values. In the provided output, the number is
negated to 1 (if initially non-zero), and the boolean value is negated to 0.

Example: Let us try overloading the increment and decrement operators through a C++ program.

#include<iostream>
using namespace std;

class UnaryOverload
{
int hr, min;
public:
void in()
{
cout<<"n Enter the time: n";
cin>>hr;
cout<<endl;
cin>>min;
}
void operator++(int) //Overload Unary Increment
{
hr++;
min++;
}
void operator--(int) //Overload Unary Decrement
{
hr--;
min--;
}

void out()
{
cout<<"nTime is "<<hr<<"hr "<<min<<"min";

}
};
int main()
{
UnaryOverload ob;
ob.in();
ob++;
cout<<"nn After Incrementing : ";
ob.out();
ob--;
ob--;
cout<<"nn After Decrementing : ";
ob.out();
return 0;

Output
Enter the time:
5
56
After Incrementing:
Time is 6hr 57 mins
After Decrementing:
Time is 4hr 55 min

Explanation
This code illustrates unary Operator overloading in C++. The UnaryOverload class represents time
in hours and minutes. It overloads the unary increment (++) and decrement (–) operators to
increment and decrement the time, respectively.

Upon execution, the program prompts the user to input the time, then increments it and displays the
result. Subsequently, it decrements the time twice and shows the final result. In the provided output,
the time is incremented from 5hr 56min to 6hr 57min and then decremented to 4hr 55min as
expected.

Example: Let us see the following C++ code that elaborates the overloading of the addition
operator.
#include <iostream>
using namespace std;
class Time {
private:
int hour;
int minute;

public:
Time() : hour(0), minute(0) {}

void in() {
cout << "Enter the time: ";
cin >> hour;
cin >> minute;
}

// Overload the + operator


Time operator + (const Time & obj) {
Time temp;
temp.hour = hour + obj.hour;
temp.minute = minute + obj.minute;
if (temp.minute>=60)
{
temp.hour+=1;
temp.minute-=60;
}
if (temp.hour>24)
temp.hour=1;
return temp;
}

void out() {
cout<<"Time is "<< hour<<"hrs "<<minute<<"min";
}
};

int main() {
Time T1, T2, result;

cout << "Enter first time in hours and minutes one by one :n";
T1.in();

cout << "Enter second time in hours and minutes one by one :n";
T2.in();

// T1 calls the operator function


// T2 is passed as an argument to the function
result = T1 + T2;
result.out();

return 0;
}

Output
Enter first time in hours and minutes one by one:
Enter the time:11
56
Enter second time in hours and minutes one by one:
Enter the time: 2
10
Time is 14hrs 6 min
Explanation
This code demonstrates binary Operator overloading in C++. The Time class represents time in
hours and minutes. The + Operator is overloaded to add two Time objects together.
Upon execution, the program prompts the user to input two times, adds them using the overloaded +
Operator, and displays the result. In the provided output, 11hrs 56min and 2hrs 10min are added
together, resulting in 14hrs 6min.

Overloading the Binary + Operator


Following is a program to demonstrate the overloading of the + operator for the class Complex.

// C++ program to overload the binary operator +


// This program adds two complex numbers

#include <iostream>
using namespace std;

class Complex
{
private:
float real;
float img;

public:
// constructor to initialize real and img to 0
Complex() : real(0), img(0) {}
Complex(float real, float img) : real(real), img(img) {}

// overload the + operator


Complex operator + (const Complex& obj1)
{
Complex temp;
temp.real = obj1.real + real;
temp.img = obj1.img + img;
return temp;
}

void display()
{
if (img < 0)
cout << "Output Complex number: " << real << img << "i";
else
cout << "Output Complex number: " << real << "+" << img << "i";
}
};

int main()
{
Complex c1(1.0f, 2.0f);
Complex c2(1.0f, 3.0f);
Complex result(0.0f, 0.0f);

// calls the overloaded + operator


result = c1 + c2;
result.display();

return 0;
}
Assuming that class X does not use any overloaded operators, write a statement that subtracts
an object of class X, x1, from another such object, x2, and places the result in x3.

x3.subtract(x2, x1);

Example: overloading + Operator to add two Time class object


#include <iostream>

class Time
{
int h,m,s;
public:
Time()
{
h=0, m=0; s=0;
}
void setTime();
void show()
{
cout<< h<< ":"<< m<< ":"<< s;
}

//overloading '+' operator


Time operator+(time);
};

Time Time::operator+(Time t1) //operator function


{
Time t;
int a,b;
a = s+t1.s;
t.s = a%60;
b = (a/60)+m+t1.m;
t.m = b%60;
t.h = (b/60)+h+t1.h;
t.h = t.h%12;
return t;
}

void time::setTime()
{
cout << "\n Enter the hour(0-11) ";
cin >> h;
cout << "\n Enter the minute(0-59) ";
cin >> m;
cout << "\n Enter the second(0-59) ";
cin >> s;
}

void main()
{
Time t1,t2,t3;

cout << "\n Enter the first time ";


t1.setTime();
cout << "\n Enter the second time ";
t2.setTime();
t3 = t1 + t2; //adding of two time object using '+' operator
cout << "\n First time ";
t1.show();
cout << "\n Second time ";
t2.show();
cout << "\n Sum of times ";
t3.show();
}

Overloading Relational Operator in C++


You can also overload relational operators like == , != , >= , <= etc. to compare two object of
any class.
Let's take a quick example by overloading the == operator in the Time class to directly compare
two objects of Time class.
#include<iostream>
using namespace std;

class Time
{
int hr, min, sec;
public:
// default constructor
Time()
{
hr=0, min=0; sec=0;
}

// overloaded constructor
Time(int h, int m, int s)
{
hr=h, min=m; sec=s;
}

//overloading '==' operator


bool operator==(Time &t1);
};

/*
Defining the overloading operator function
Here we are simply comparing the hour, minute and
second values of two different Time objects to compare
their values
*/
bool Time::operator== (Time &t1)
{
return ( t1.hr == hr && t1.min == min && t1.sec == sec );
}

int main()
{
Time t1(3,15,45);
Time t2(3,15,45);
if(t1 == t2)
{
cout << "Both the time values are equal";
}
else
{
cout << "Both the time values are not equal";
}
}
Copy Constructor vs. Assignment Operator (=)
Assignment operator is used to copy the values from one object to another already existing
object. For example:
Time tm(3,15,45); // tm object created and initialized
Time t1; // t1 object created
t1 = tm; // initializing t1 using tm

Whereas, Copy constructor is a special constructor that initializes a new object from an existing
object.
Time tm(3,15,45); // tm object created and initialized
Time t1(tm); //t1 object created and initialized using tm object

In case of Copy constructor, we provide the object to be copied as an argument to the constructor.
Also, we first need to define a copy constructor in our class.

You might also like