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

Chapter 5 Operator Overloading

Hdhjcjb

Uploaded by

lijbelay7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Chapter 5 Operator Overloading

Hdhjcjb

Uploaded by

lijbelay7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Chapter Five Operator Overloading

Operator overloading
C++ allows you to specify more than one definition for a function name or an operator in the same
scope, which is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that had been declared with the same name as a
previously declared declaration in the same scope, except that both declarations have different
arguments and obviously different definition (implementation).
Operators overloading in C++:
You can overload one of the standard C++ operators by redefining it to perform a particular
operation when you apply it to an object of a particular class. Overloaded operators must have at
least one argument that has class type. Thus a programmer can use operators with user-defined types
as well.
Following is the list of operators which can be overloaded:
+ - * / % ^

& | ~ ! , =

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

|= *= <<= >>= [] ()

-> ->* New new [] Delete delete []


Rules for operator overloading
In C++, following are the general rules for operator overloading.
a) Only built-in operators can be overloaded. New operators cannot be created.
b) Precedence and associativity of the operators cannot be changed.
c) Overloaded operators cannot have default arguments except the function call operator () which
can have default arguments.
d) Operators cannot be overloaded for built in types only. At least one operand must be used
defined type.
e) Assignment (=), subscript ([]), function call (“()”), and member selection (->) operators must be
defined as member functions
f) Except the operators specified in point (e), all other operators can be either member functions or
a non-member functions.
g) Some operators like (assignment) =, (address) & and comma (,) are by default overloaded.

Restrictions on Overloaded Operators


 You cannot overload the following C++ operators:
. .* :: ?:
 You cannot overload the preprocessing symbols # and ##.
 You cannot change the precedence, grouping, or number of operands of the standard C++
operators.

DBU, Department of Information Technology Page 1


Chapter Five Operator Overloading

 An overloaded operator (except for the function call operator) cannot have default arguments
or an ellipsis in the argument list.
 You must declare the overloaded =, [], (), and -> operators as non-static member functions to
ensure that they receive values as their first operands.
 All operators except the = operator are inherited. Copy by Assignment describes the
behavior of the assignment operator.
Operator Overloading Examples
Here are various operator overloading examples to help you in understanding the concept.
 Unary operators overloading
 Binary operators overloading
 Relational operators overloading
 Input/output operators overloading
 ++ and -- operators overloading
 Assignment operators overloading
 Function call () operator overloading
 Subscripting [] operator overloading
 Class member access operator -> overloading
Unary Operators Overloading
The unary operators operate on a single operand and following are the examples
of Unary operators:
 The increment (++) and decrement (--) operators.
 The unary minus (-) operator.
 The logical not (!) operator.
Following example explain how minus (-) operator can be overloaded for prefix
as well as postfix usage.
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// method to display distance
void displayDistance()
{
cout << "Feet: " << feet << " Inches:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- ()
{

DBU, Department of Information Technology Page 2


Chapter Five Operator Overloading

feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main()
{
Distance n1(6, 10), n2(-5, 11);
-n1; // apply negation
n1.displayDistance(); // display n1
-n2; // apply negation
n2.displayDistance(); // display n2
return 0;
}
When the above code is compiled and executed
Feet: -6 Inches:-10
Feet: 5 Inches:-11
Binary Operators overloading
The binary operators take two arguments and following are the examples of Binary operators. You
use binary operators very frequently like addition (+) operator, subtraction (-) operator,
multiplication (*) operator and division (/) operator. 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&);
Declares the addition operator that can be used to add two Box objects and returns final Box
object. Most overloaded operators may be defined as ordinary non-member functions or as class
member functions.
Box operator + (const Box&, const Box&);
Following is the example to show the concept of operator over loading using a member function.
Here an object is passed as an argument whose properties will be accessed using this object; the
object which will call this operator can be accessed using this operator as explained below:
#include <iostream>
using namespace std;
class Box
{
double length;
double breadth;
double height;
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;

DBU, Department of Information Technology Page 3


Chapter Five Operator Overloading

}
void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
};
// Main function for the program
int main( )
{
Box Box1;
Box Box2;
Box Box3;
double volume = 0.0;
// box 1 specification
Box1.setLength(2.0);
Box1.setBreadth(3.0);
Box1.setHeight(4.0);
// box 2 specification
Box2.setLength(10.0);
Box2.setBreadth(1.0);
Box2.setHeight(6.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 24
Volume of Box2 : 60
Volume of Box3 : 480
Relational Operators Overloading
There are various relational operators supported by C++ language like (<, >, <=, >=, ==,etc.) which

DBU, Department of Information Technology Page 4


Chapter Five Operator Overloading

can be used to compare C++ built-in data types. You can overload any of these operators, which can
be used to compare the objects of a class.
Following example explains how a < operator can be overloaded and similar way
you can overload other relational operators.
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
// method to display distance
void displayDistance()
{
cout << "Feet: " << feet << " Inches:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- ()
{
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
// overloaded < operator
bool operator <(const Distance& d)
{
if(feet < d.feet)
{
return true;
}
if(feet == d.feet && inches < d.inches)
{
return true;
}
return false;
}
};
int main(){
Distance n1(11, 10), n2(5, 11);
if( n1 < n2 )

DBU, Department of Information Technology Page 5


Chapter Five Operator Overloading

{
cout << "n1 is less than n2 " << endl;
}
else
{
cout << "n2 is less than n1 " << endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
n2 is less than n1
Assignment Operator Overloading
You can overload the assignment operator (=) just as you can other operators
and it can be used to create an object just like the copy constructor.
Following example explains how an assignment operator can be overloaded.
#include <iostream>
using namespace std;
class Distance
{
private:
int feet;
int inches;
public:
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
void operator=(const Distance &D )
{
feet = D.feet;
inches = D.inches;
}
// method to display distance
void displayDistance()
{
cout << "Feet: " << feet << " Inches:" << inches << endl;
}
};
int main()
{
Distance n1(11, 10), n2(5, 11);
cout << "First Distance : ";
n1.displayDistance();
cout << "Second Distance :";
n2.displayDistance();
// use assignment operator

DBU, Department of Information Technology Page 6


Chapter Five Operator Overloading

n1 = n2;
cout << "First Distance :";
n1.displayDistance();
return 0;
}
When the above code is compiled and executed, it produces the following result:
First Distance: Feet: 11 Inches:10
Second Distance :Feet: 5 Inches:11
First Distance :Feet: 5 Inches:11
Function Call () Operator Overloading
The function call operator () can be overloaded for objects of class type. When you overload ( ), you
are not creating a new way to call a function. Rather, you are creating an operator function that can
be passed an arbitrary number of parameters.
Subscripting [ ] Operator Overloading
The subscript operator [] is normally used to access array elements. This operator can be overloaded
to enhance the existing functionality of C++ arrays.

DBU, Department of Information Technology Page 7

You might also like