Operator Overloading
Operator Overloading
Introductio
n
• Operator overloading
Enabling C++’s operators to work with class objects
Using traditional operators with user-defined objects
Examples of already overloaded operators
• Operator << is both the stream-insertion
operator and the bitwise left-shift operator
• Operator >> is both the stream-extraction
operator and the
bitwise right-shift operator
Compiler generates the appropriate code based
on the manner in which the operator is used.
Introduction
(Cont…)
• Overloading an operator
– Write function definition as normal
– Function name is keyword operator followed by the
symbol for the operator being overloaded
– For e.g., operator+ used to overload the addition operator
(+)
• Using operators
– To use an operator on a class object, it must be overloaded unless the
assignment operator (=) or the address operator (&)
• Assignment operator by default performs memberwise assignment
• Address operator (&) by default returns the address of an object
Restrictions on Operator
Overloading
• Overloading restrictions
– Precedence of an operator cannot be changed
– Associativity of an operator cannot be changed
– number of operands cannot be changed
• Unary operators remain unary, and binary operators remain binary
• Operators &, *, + and - each have unary and binary versions
• Unary and binary versions can be overloaded separately
• No new operators can be created
– Use only existing operators
• No overloading operators for built-in types
– Cannot change how two integers are added
– Produces a syntax error
What are Operators in C++?
• Arithmetic Operators: +, −, /, ∗, %
• Assignment Operators: +=,+=, −=,−=, /=,/=, ∗=,∗=, %=%=
• Relational Operators: ==,==, !=,!=, >=,>=, <=,<=,etc.
• Logical Operators: &&,&&, ∣∣,∣∣, !!
• Bitwise Operators: &,&, ∣,∣, >>, <<etc.
• Other Operators: sizeof, ?:,etc.
Restrictions on Operator
Overloading
• All the C++ operators can be overloaded except the following:
• Scope Resolution Operator (::)
• Conditional Operator (? :)
• Size Operator (sizeof)
• Class Member Access Operators (. and .*)
Operator Functions as Class Members vs. as
friend Functions
Note: If left operand is of a different type than class, operator function must be a non-member function
C++ Syntax for Operator Overloading
• class ClassName{
•
• private:
• ...............
•
public:
• ...............
•
• <ReturnType> operator <operator> (arguments){
• ...............
• ...............
• }
• ...............
• };
Creating a Member Operator Function
int main()
{ -D1; // activates operator-() function
Distance
D1.displayDistance(); // D1display Output:
D1(11,
-D2; 10), // activates operator-() function F: -11 I:-10 F: 5 I:-11
D2(-5, 11);
D2.displayDistance(); // display
D2 return 0;
}
Binary
Operators
• The binary operators take two arguments.
return pointer_to_memory; }
}
Example
#include <iostream> // new overloaded relative to loc
using namespace std; void *loc::operator new(size_t size)
class loc { {
int longitude, latitude; void *p;
public: cout << "In overloaded new.\n";
loc() {} p = malloc(size);
loc(int lg, int lt) return p;
longitude = lg; }
latitude = lt; // delete overloaded relative to loc
} void loc::operator delete(void *p)
void show() { {
cout << longitude << " "; cout << "In overloaded delete.\n";
cout << latitude << "\ free(p);
n"; }
}
void *operator
new(size_t size);
void operator
delete(void *p);
Continued
…
int main()
{
loc *p1, *p2;
• Given an object called obj, the expression obj[3] translates into this
call to the operator[ ]( ) function: obj.operator[](3)
Example 1
#include <iostream> int operator[](int i)
using namespace std; { return a[i];
class atype { }
int a[3]; };
public: int main()
atype(int i, int j, int k) { {
a[0] = i; atype ob(1, 2, 3);
a[1] = j; cout << ob[1]; // displays 2
a[2] = k; return 0;
} } Output:
2
Example
2
#include <iostream> int main()
using namespace std; {
class atype { atype ob(1, 2, 3);
int a[3]; cout << ob[1]; // displays 2
public: cout << " ";
atype(int i, int j, int k) { ob[1] = 25; // [] on left of =
a[0] = i; cout << ob[1]; // now displays 25
a[1] = j; return 0;
a[2] = k; }
}
int &operator[](int i) { Output:
return a[i]; 2 25
}
};
Overloading
()
• When we overload the ( ) function call operator, we are
not creating a new way to call a function.
Example:
double operator()(int a, float f, char *s);
and an object O of its class, then the statement
O(10, 23.34, "hi");
translates into this call to the operator( ) function.
O.operator()(10, 23.34, "hi");
Example
#include <iostream>
using namespace std; // Overload + for loc
class loc { loc loc::operator+(loc op2)
int longitude, {
latitude; loc temp;
public: temp.longitude = op2.longitude + longitude;
loc() {} temp.latitude = op2.latitude + latitude;
loc(int lg, int lt) return temp;
{ }
longitude = lg;
latitude = lt;
} int main()
void show() { {
cout << loc ob1(10, 20), ob2(1, 1);
longitude << " ob1.show();
"; ob1(7, 8); // can be executed by itself
cout << ob1.show();
latitude << "\ ob1 = ob2 + ob1(10, 10); // can be used in expressions
n"; ob1.show();
} return 0;
loc operator+(loc op2); }
loc operator()(int i, int j);
};
// Overload ( ) for loc
loc loc::operator()(int i,
Overloading the Comma
Operator
#include <iostream> cout << op2.longitude << " " << op2.latitude << "\n";
using namespace std; return temp;
class loc { }
int longitude, // Overload + for loc
latitude; loc loc::operator+(loc op2)
public: {
loc() {} loc temp;
loc(int lg, int lt) { temp.longitude = op2.longitude + longitude;
longitude = lg; temp.latitude = op2.latitude + latitude;
latitude = lt; return temp;
} }
void show() { int main()
cout << longitude << " "; {
cout << latitude << "\ loc ob1(10, 20), ob2( 5, 30), ob3(1, 1);
n"; ob1.show();
} ob2.show();
loc operator+(loc op2); ob3.show();
loc operator,(loc op2); cout << "\n";
}; ob1 = (ob1,
// overload comma ob2+ob2,
for loc ob3);
loc loc::operator,(loc ob1.show();
op2) // displays 1
{ 1, the value
Overloading
->
• The –> pointer operator, also called the class member access operator,
is considered a unary operator when overloading.
O
Type
Conversions
• When constants and variables of different types are mixed in an
expression, C++ applies automatic type conversion to the operand
as per certain rules. Similarly, an assignment operator also causes
the automatic type conversion.
• The type conversions are automatic as long as the data types
involved are built-in types.
Using constructor
Using Operator Overloading
Example (Using
Constructor)
// Program to convert basic type to class type using constructor
int main()
#include <iostream>
{
using namespace std; int duration;
class Time { cout<<"Enter time duration in minutes";
int hrs, min; cin>>duration;
public: Time t1=duration;
t1.display();
Time (int);
return 0;
void display(); }
};
Time :: Time (int t)
{
cout<<"Basic Type to ==> Class Type Conversion..."<<endl;
During type conversion using the
constructor we can pass only one
hrs=t/60;
argument and we can do type
min=t%60;
conversion at the type of
}
initialization only.
void Time::display()
{ cout<<hrs<< ": Hours(s)" <<endl; cout<<min<< " Minutes" <<endl;
}
Using Operator
Overloading
• Type conversion from basic to class type can also be done by
operator overloading.
operator typename( )
{
//Function statements
}
Continued
…
• The conversion function should satisfy the following condition:
// casting
operator function
~Time() //
destructor
{
cout<<"Destruct
or
called..."<<endl;
}
};
Continued…
Time :: operator int()
{
cout<<"Class Type to Basic Type Conversion..."<<endl;
return(hrs*60+min);
}
int main()
{
int h, m, duration;
cout<<"Enter Hours ";
cin>>h; cout<<"Enter
Minutes ";
cin>>m;
Time t(h,m); // construct object
duration = // casting conversion OR duration = (int)t
t;
cout<<"Total Minutes are "<<duration;
cout<<"2nd method operator overloading "<<endl;
duration = t.operator int();
cout<<"Total Minutes are "<<duration;
return 0;
}
Class to Class
Type
• In this type of conversion both the type that is source type and
the destination type are of class type.