0% found this document useful (0 votes)
19 views30 pages

PPT8 - Operator Overleading

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)
19 views30 pages

PPT8 - Operator Overleading

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/ 30

UTA 018: OOPs

Poly-morphism
(Operator Overloading)

1
Introduction

• 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
Introduction (Cont…)
• Overloading an operator
– Write function definition as normal
– Functionname is keywordoperator followed bythe symbol for the
operator being overloaded
– For e.g., operator+ used to overload the addition operator (+)

Returntype operator+(arg list){


//body
}
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
• 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
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

• Operator functions can be either member or non- member


functions of a class.
• Operator functions as member functions
– Leftmost operand must be an object of the class
• Operator functions as non-member functions
– Must be friend functions of the class
– Enables the operator to be commutative

Note: If left operand is of a different type than class, operator function must be a non-member function
Creating a Member Operator Function

returntype classname::operator opname(arg-list)


{
// operations
} Keyword
Overloading of Unary Operator - (using member function)
Complex Class Example
Continued…
Overloading using Friend Functions
• There are certain situations where we would like to use a
friend function rather than a member function.
• For example, if we want to use two different types of a binary
operator, say, one an object and another a built in type as
shown below:
A=B+2, where A and B are objects of same class. This will
work for a member function, but the statement A=2+B; will
not work.
• This is because the left-handed operand which is responsible
for invoking the membership function should be an object of
the same class.
• Friend function allows both approaches as it is invoked
without the use of objects.
Continued…
• Unary operators, overloaded by means of a member function,
take no explicit arguments, but, those overloaded by means
of a friend function, take one reference argument (the object
of the relevant class).

• Binary operators overloaded through a member function take


one explicit argument and those which are overloaded
through a friend function take two explicit arguments.

• When using binary operators overloading through member


function, the left hand operand must be an object of the
relevant class.
Restrictions on application of friend function
• Operators that can not be overloaded using a friend
function are:
= Assignment operator
() Function call operator
[] Subscript operator
-> Class Member Access Operator
Overloading new and delete
// Allocate an object // Delete an object
void *operator new(size_t size) void operator delete(void
{ *p)
/* Perform allocation. Throw {
bad_alloc on failure. /* Free memory pointed to by p.
Constructor called Destructor called
automatically. */ automatically. */
return pointer_to_memory; }
}
Example
#include <iostream> // new overloaded relative to loc
using namespace std; class loc { void *loc::operator new(size_t size)
int longitude, latitude; public: {
loc() {} void *p;
loc(int lg, int lt) longitude = lg; cout << "In overloaded new.\n";
latitude = lt; p = malloc(size);
} return p;
void show() { }
cout << longitude << " "; cout << latitude << // delete overloaded relative to loc void
"\n"; loc::operator delete(void *p)
} {
void *operator new(size_t size); cout << "In overloaded delete.\n"; free(p);
void operator delete(void *p); }
};
Continued…
int main()
{
loc *p1, *p2;

p1 = new loc (10, 20);


p2 = new loc (-10, -20);
}
p1->show();
p2->show();
delete p1; delete p2;
return 0;
}
Overloading [ ] operator
• In C++, the [ ] is considered a binary operator when you are
overloading it.

• Therefore, the general form of a member operator[ ]( ) function is as


shown here:
returntype classname::operator[](int i)
{
// . . .
}

• Technically, the parameter does not have to be of type int, but an


operator[ ]( ) function is typically used to provide array subscripting,
and as such, an integer value is generally used.

• 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; }
}
Output:
int &operator[](int i) {
return a[i]; 2 25
}
};
Overloading ()
• When we overload the ( ) function call operator, we 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.

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> // Overload + for loc
using namespace std; loc loc::operator+(loc op2)
class loc { {
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;
}
void show() { int main()
cout << longitude << " "; {
cout << latitude << "\n"; loc ob1(10, 20), ob2(1, 1);
} ob1.show();
loc operator+(loc op2); loc operator()(int i, int j); ob1(7, 8); // can be executed by itself
}; ob1.show();
// Overload ( ) for loc ob1 = ob2 + ob1(10, 10); // can be used in expressions
loc loc::operator()(int i, int j) ob1.show();
{ return 0;
longitude = i; latitude = j; }
return *this;
}
Overloading the Comma Operator
#include <iostream> cout << op2.longitude << " " << op2.latitude << "\n";
return temp;
using namespace std;
}
class loc {
// Overload + for loc
int longitude, latitude;
loc loc::operator+(loc op2)
public:
{
loc() {}
loc temp;
loc(int lg, int lt) { longitude = lg; latitude = lt;
temp.longitude = op2.longitude + longitude;
}
temp.latitude = op2.latitude + latitude; return temp;
void show() {
cout << longitude << " "; cout << latitude << "\n"; }
} int main()
loc operator+(loc op2); loc operator,(loc op2); {
loc ob1(10, 20), ob2( 5, 30), ob3(1, 1);
};
ob1.show();
// overload comma for loc
ob2.show();
loc loc::operator,(loc op2)
ob3.show(); cout << "\n";
{
loc temp; ob1 = (ob1, ob2+ob2, ob3);
temp.longitude = op2.longitude; temp.latitude = ob1.show(); // displays 1 1, the value of ob3
op2.latitude; return 0;
}
Overloading ->
• The –> pointer operator, also called the class member access operator,
is considered a unary operator when overloading.

• Its general usage is shown here:


object->element;
• Here, object is the object that activates the call. The operator–>( )
function must return a pointer to an object of the class that operator–>(
) operates upon.

• The element must be some member accessible within the object.

• The example illustrates overloading the –> by showing the equivalence


between ob.i and ob–>i when operator–>( ) returns this pointer:
Example
• #include <iostream> using int main()
namespace std; class {
myclass { myclass ob;
• public: ob->i = 10;
• int i; // same as ob.i
• myclass *operator->() cout << ob.i << " " << ob->i;
• { return 0;
• return this; }
• }
• }; Output:
10 10
Thanks

You might also like