You are on page 1of 62

CSE1002 - Problem Solving and Object Oriented

Programming

M.MANORANJITHAM
Assistant Professor
SCOPE
VIT Chennai

04/22/2024 CSE1002 1
Operator overloading

04/22/2024 CSE1002 2
Operator overloading
• Operator overloading is one of the many exciting features of C++ programming
language.
• It is an important technique that has enhanced or increase the power of extensibility of
c++.
• We have stated more than once that c++ language tries to make the user defined data
types behaves in much the same way as the built-in-types.
• For instance, c++ language permits us to add two variables of user-defined types with
the same syntax that is applied to the basic types.
• This means that c++ has the ability to provide the operators with a special meanings to
an operator is known as operator overloading.
• Operator overloading provides a flexible option for the creation of new definitions for
most of the c++ programming operators.
• We can almost create a new language of our own by creative use of the function and
operator overloading techniques.
04/22/2024 CSE1002 3
Operator Overloading…?
• Changing the definition of an operator
• it can be applied on the objects of a class is called operator
overloading
• C++ already has a number of types (e.g., int, float, char, etc.) that each
have a number of built in operators.
• For example, a float can be added to another float and stored in yet another
float with use of the + and = operators:
floatC = floatA + floatB;
• In this statement, floatB is passed to floatA by way of the + operator. The +
operator from floatA then generates another float that is passed to floatC
via the = operator. That new float is then stored in floatC by some method
outlined in the = function.

04/22/2024 CSE1002 4
Most of C++’s operators can be overloaded
Operators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]

04/22/2024 CSE1002 5
• We can overload(give additional meaning to) all the c++ operators
except the following:
● Class member access operators ( ., . *).
● Scope resolution operator (: :).
● Size operator (sizeof).
● Conditional operator (?:).

• The excluded operators are very few when compared to the large
number of operators which qualify for the operator overloading
definition.

04/22/2024 CSE1002 6
• Although the semantics of an operator can be extended,
we can’t change its syntax, the grammatical rules that
govern its use such as the number of operands,
precedence and associativity.
• Example
• manipulation operator will enjoy higher precedence then the
addition operator.
• Note, when an operator is overloaded, its original
meaning is not lost.
• For instance, the operator +, which has been overloaded
two add two vectors, can still be used to add two integers.
04/22/2024 CSE1002 7
Defining Operator Overloading
• To define an additional task to an operator, we must specify what it means in
relation to the class to which the operator is applied. This is done with the help
of a special function, called operator function, which describes the task.
• The general form of an operator function is:
return type classname: : operator (op –arglist)
{
Function body // task defined
}
• Where return type is the type of value returned by the specified operation and op
is the operator being overloaded.
• The op is preceded by the keyword operator.
• Operator op is the function name.
04/22/2024 CSE1002 8
General syntax of Operator Overloading
Returntype operator operatorsign ( signatures )
{ For example:
statement 1 We have class named sum
then
statement 2
} Sum operator + (sum object)
{

statement 1
statement 2
}

04/22/2024 CSE1002 9
• Operator function must be either member functions (non – static) or
friend functions.
• A basic difference between them is that a friend function will have
• only one argument for unary operators and two for binary operators,
• while a function has no arguments for unary operators and only one for
binary operators.
• it is because the object used to invoke the member function is passed
implicitly and therefore is available for the member function.
• This is not the case with friend functions.
• Arguments may be passed either by value or by reference.

04/22/2024 CSE1002 10
Operator functions are declared in the class using prototypes as follows:

• vector is a data type of class and may represent both magnitude and
direction (as in physics and engineering) or a series of points called
elements ( as in mathematics).

04/22/2024 CSE1002 11
• The process of overloading involves the following steps:

• 1. Create a class that defines the data type that is to be used in


the overloading operation.

• 2. Declare the operator function operator op() in the public


Area of the class. It may be either a member function or a
friend function.

• 3. Define the operator function to implement the required


operations.

04/22/2024 CSE1002 12
Overloaded operator functions can be invoked by expressions such as
• op x or x op  for unary operators and

• x op y for binary operators. Op x(or x op) would be


interpreted as

• operator op (x)  for friend functions. Similarly the


expression x op y would be interpreted as either

• x.operator op (y)  in case of friend functions. When both


the forms are declared, standard argument matching is applied to
resolve any ambiguity.
04/22/2024 CSE1002 13
How the operator function is called
• There are two ways
• Implicit calling
• Explicit calling

• Implicit calling
• If compiler calls an operator function automatically, such as
object1= object2+ object3

• Explicit Calling
• If the operator function is manually called by user, such as
object1= object2.operator + object3
04/22/2024 CSE1002 14
Types of Operator
• Unary operator
• Binary operator

04/22/2024 CSE1002 15
Overloading
-
Unary Operators

04/22/2024 CSE1002 16
Unary Operators
• Operators attached to a single operand
• -a
• +a
• --a
• a--
• ++a
• a++

04/22/2024 CSE1002 17
Syntax for overloading unary operators

04/22/2024 CSE1002 18
unary minus operator
• A minus operator used when as a unary, takes just only one operand.
• We know that this operator changes the sign of an operand when
applied to a basic one operand.
• The minus unary when applied to an object when should change the
sign of each of its data items.

04/22/2024 CSE1002 19
-

04/22/2024 CSE1002 20
• Note: This function operator -() takes no argument. Then

what does this operator function do?


• It changes the sign of data members of the object S.
• since this function is a member function of the same class, it can directly
access the members of the object which activated it.
• Remember, a statement like
s2=-s1;
• Will not work because, the function operator-() does not return any value.it
can work if the function is modified to return an object.

04/22/2024 CSE1002 21
• it is possible to overload a unary minus operator using a friend function as
follows:

Friend void operator-(space &s); // declaration


void operator-(space &s) // definition
{
s.x=-s.x;
s.y=-s.y;
s.z=-s.z;
}
• Note: That the argument is passed by reference, it will not work if we pass argument
by value because only a copy of the object that activated the call is passed to
operator-() Therefore, the changes made inside the operator function will not reflect
in the called object.
04/22/2024 CSE1002 22
Overloading

BInary Operators

04/22/2024 CSE1002 23
Binary Operators
• Operators attached to two operands
• a-b
• a+b
• a*b
• a/b
• a%b
• a>b, a>=b, a<b, a<=b, a==b)

04/22/2024 CSE1002 24
Overloading Binary Operators
• A binary operator can be overloaded as a non-static member function
with one parameter or as a non-member function with two parameters
(one of those parameters must be either a class object or a reference to
a class object).
• As a non-member function, binary operator < must take two
arguments—one of which must be an object (or a reference to an
object) of the class.

04/22/2024 CSE1002 25
Overloading Binary Operators
• Similar to overload a unary operator mechanism, we can be used to
overload the binary operator.
• A statement like
C = sum(A, B); // it is functional notation.
• was used. The functional notation can be replaced by a natural looking
expression
c = A + B; // arithmetic notation

04/22/2024 CSE1002 26
Syntax for overloading a binary operator

04/22/2024 CSE1002 27
Binary operators
• Assignment operator
• Arithmetic operators
• Arithmetic assignment operators
• Relational operators

04/22/2024 CSE1002 28
Arithmetic operator

(+)

04/22/2024 CSE1002 29
04/22/2024 CSE1002 30
• Note: Let us have a close look at the function operator+ () and see how
the operator overloading is implemented.
Complex complex : : operator+ (complex c)
{
complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return(temp) ;
}
• We should note the following features of this function:
1) It receives only one complex type argument explicitly.
2) It returns a complex type value.
3) It is a member function of complex
04/22/2024 CSE1002 31
• The function is expected to add two complex values and return a complex
value as the result but receives only one value as argument.
• When does the other value come from?
• Now let us look at the statement that invokes this function:
C3 = C1 + C2; // invokes operator+() function
• We know that a member function can be invoked only by an object of the same
class. Here, the object c1 takes the responsibility of invoking the function and
c2 plays the role of an argument that is passed to the function.
• The above invocation statement is equivalent to
C3 = C1. operator+(C2); // usual function call syntax
• Therefore, in the operator+() function, the data members of C1 are accessed
directly and the data members of c2 (that is passed as an argument ) are
accessed using the dot operator. Thus, both the objects are available for the
function.
04/22/2024 CSE1002 32
• For example, in the statement
temp.x = x + c.x;
• c.x refers to the object c2 and x refers to the object C1.temp.x is the
real part of temp that has been created specially to hold the results of
addition of C1 and C2.
• The function returns the complex temp that has been created
specially to hold the results of addition of C1 and C2.
• The function returns the complex temp to be assigned to C3.

04/22/2024 CSE1002 33
04/22/2024 CSE1002 34
• As a rule, in overloading of binary operators, the left-hand operand is used to
invoke the operator function and the right-hand operand is passed as an
argument.
• We can avoid the creation of the temp object by replacing the entire function
body by the following statement:
return complex((x+c.x) , (y+c.y)); // invokes constructor 2
• What does it mean when we use a class name with an argument list?
• When the complier comes across a statement like this, it invokes an appropriate
constructor, initializes an object with no name and returns the contents for copying into
an object.
• Such an object is called a temporary object and goes out of space as soon as soon as
the contents are assigned to another object.
• Using temporary objects can make the code shorter, more efficient and better to read.

04/22/2024 CSE1002 35
04/22/2024 CSE1002 36
Overloading
binary operators
using friends

04/22/2024 CSE1002 37
• Let us consider the program of complex number we seen before,that
can be modified using a friend operator function as follows:

1) Replace the member declaration by the friend function declaration.


friend complex operator+(complex,complex);

2) Redefine the operator function as follows:


complex operator+(complex a, complex b)
{
return complex (( a.x + b.x), (a.y+b.y));
}
04/22/2024 CSE1002 38
In this case, the statement
C3 = C1+ C2;
Is equivalent to
C3 = operator+(C1 , C2);
• In the most cases, we get the same results by the use of either a member
function or a friend function.
• Why then an alternative is made available?
• There are certain conditions where we would like to use a friend function rather
than a member function.

04/22/2024 CSE1002 39
• For instance, consider the situation where you need to use two different
types of operands for a binary operator, say, one an object and another a
built in type data as shown in below,
A= B +2; (or A = B * 2;)
• Where in the above example A and B are objects of the same class. it will
work for a member function but the statement
A = 2 + B; (or A = 2 * B)
• will not work. it is because the left-hand operand which is responsible for
invoking the member function should be an object of the same class.
• However friend function allows both approaches. How?

04/22/2024 CSE1002 40
However friend function allows both approaches. How?
• it may be re-called that an object need to be used to invoke a friend
function but can be passed as an argument.
• Thus, we can use a friend function or(method) with a built in type data as
the left hand operand and an object as the right hand operand.

04/22/2024 CSE1002 41
Overloading the
input and output operators
>> and<<

04/22/2024 CSE1002 42
Overload the input and output operators >> and<< using
the scalar multiplication of a vector and using friends.

04/22/2024 CSE1002 43
04/22/2024 CSE1002 44
04/22/2024 CSE1002 45
Assignment operator

(=)

04/22/2024 CSE1002 46
Assignment Operator example
#include<iostream.h> assignment temp;
#include<conio.h> temp.a=obj.a;
class assignment return (temp);
{
}
int a;
};
public:
void main ( )
void get(int x)
{
{
a=x; assignment obj1, obj2;
} obj1.get(3);
void show() obj1.show();
{ obj2=obj1;
cout << “ value of a = “<<a; cout<<“\nvalue of data member of obj2 after
} copying is “<<endl;
assignment operator =(assignment obj) obj2.show();
{ getch();
04/22/2024
}
CSE1002 47
Arithmetic Assignment operator

(-=)

04/22/2024 CSE1002 48
Arithmetic Assignment Operator
class arithassgnopt void main ( )
{ {
int a; arithassgnopt obj1, obj2;
public:
obj1.get(6);
void get(int x)
obj2.get(2);
{
cout<<“\n value of the data membera of obj1 is<<endl;
a=x;
obj1.show();
}
void show()
obj1 -=obj2;
{ cout<<“\nvalue of data member a of obj1 after overloading -=
cout<<a; is “;
} obj1.show();
void operator -=(arithassgnopt obj) getch();
{ }
a-=obj.a;
}
}; 04/22/2024 CSE1002 49
Incremental operator

(++)

04/22/2024 CSE1002 50
Incremental operator overloading
class increment
{
int a;
public:
void get (int x ) void main ( )
{ {
a=x;
increment obj1;
}
void show()
obj1.get(10);
{ obj1.show();
cout<<a; obj1++;
} obj1.show();
void operator ++ () getch();
{ }
++a;
}
};
04/22/2024 CSE1002 51
Relationaloperator

(>)

04/22/2024 CSE1002 52
Operator overloading “>”
#include<iostream.h>
void main()
#include<conio.h>
{
class relational
relational obj1, obj2;
{
obj1.get(2);
int a;
obj2.get(10);
public:
if(obj1 > obj2)
void get(int x)
cout<<"\nobject 1 is greater than obj2";
{
else
a=x;
cout<<"\nobject 1 is smaller than obj2";
}
getch();
int operator > (relational obj)
}
{
if (a>obj.a)
return 1;
else
return 0;
04/22/2024 CSE1002 53
}
Rules For Overloading Operators
Although it looks simple to redefine the operators, There are certain
restrictions and limitations in overloading them, some of them are listed
below
1) Only existing operators can be overloaded. now operators cannot be
created
2) The overloaded operator must have at least one operand that is type of
user defined.
3) We can’t change the basic meaning of an operator. That is to say we
cannot redefine the plus(+) operator to subtract one value from the other.
4) The Overloaded operators follows the rules of the original operators.
They cannot be overridden.
5) There are some operators that can’t be overloaded.
04/22/2024 CSE1002 54
Rules For Overloading Operators
6) we can’t use friend functions to overload certain operators. however
the member function can be used to overload them .
7) The unary operators, overloaded by the member function, take no
explicit arguments and also no explicit values return, but those
overloaded by means of a friend function, take one reference argument.
8) Binary operator overloaded through a member function take two
explicit arguments
9) When using the binary operators overloaded using a member function,
the left hand side operand must be an object of the relevant class.
10) Binary arithmetic operators such as *,+,- and / must be explicitly return
the value, they must not attempt to change their own arguments.

04/22/2024 CSE1002 55
Manipulation of string using operators
• In C implements string character arrays, pointers and string functions.
• There are no operators for manipulation the strings.
• once of the main drawbacks of string manipulations in C is that
whenever a string is to be copied, The programmer must fist determine
its length and allocate the required amount of memory

04/22/2024 CSE1002 56
• Although these limitations exist in C++ as well, its permits us to create
own definitions of operators that can be used to manipulation the any
string very much similar to the decimal number class library that supports
all types of string manipulations.

• For example, we shall be able to use statements like

string3=string1+string2;
if(string1>=string2) string =string1;

04/22/2024 CSE1002 57
• string can be defined as class objects which can be then manipulated like the built in types.
• since the strings vary greatly in size, we use new operator to allocate memory for each string
and a pointer variable to point to the string array.
• Thus we must create string objects that can hold these two pieces of information, namely,
locations and length which are necessary for string manipulations.
• A typical string class will look as follows

class string
{
char *p; // pointer to string
int len; // length of string
public:
……. // member functions
…… // to initialize and
……. // manipulate strings
04/22/2024
}; CSE1002 58
04/22/2024 CSE1002 59
04/22/2024 CSE1002 60
04/22/2024 CSE1002 61
04/22/2024 CSE1002 62

You might also like