0% found this document useful (0 votes)
13 views70 pages

SDF Operator Overloading

The document provides an overview of operator and function overloading in C++, detailing how to define multiple meanings for operators and functions based on user-defined types. It explains the syntax for overloading operators, the types of operators that can be overloaded, and the restrictions associated with operator overloading. Additionally, it includes examples and code snippets demonstrating the implementation of various overloaded operators.

Uploaded by

singhaladi418
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)
13 views70 pages

SDF Operator Overloading

The document provides an overview of operator and function overloading in C++, detailing how to define multiple meanings for operators and functions based on user-defined types. It explains the syntax for overloading operators, the types of operators that can be overloaded, and the restrictions associated with operator overloading. Additionally, it includes examples and code snippets demonstrating the implementation of various overloaded operators.

Uploaded by

singhaladi418
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/ 70

Jaypee Institute Of Information Technology (JIIT),

Noida

SDF II (15B11CI211)

Lecture 10-11 – Operator Overloading & Function Overloading

1
Objectives
• Overloading in C++
– Function overloading
– Operator overloading
• Different types of operators and their
overloading
• Operators that cannot be overloaded
C++ Overloading

• Overloading in C++ allows 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.
C++ Overloading
C++ OVERLAODING

Function Operator

• An overloaded declaration is the one that had


been declared with exactly the same name as
the previous declaration in the same scope,
except that both declarations have different
arguments and also different definition
(implementation).
C++ Function Overloading
• An overloaded function can have multiple definitions for
the same function name in the same scope.

• The definition of the function must differ from each other


by the types and/or the number of arguments in the
argument list.

• Function declarations cannot be overloaded if they differ


only by return type.
Operator Overloading
Operator Overloading
• Operator Overloading is an important
technique that has enhanced the power of
extensibility of C++
• C++ tries to make user defined data types
behave in the same way as the built in types.
• For example C++ permits us to add two
variables of user defined types with the same
syntax that is applied to basic data types.
What does it mean?
• Giving some special meaning to the operators to enable them
to operate on user defined data types.

• Operator overloaded retains its original meaning.


(say if * is overloaded to multiply two class objects and can
always be used multiply two numbers)
Example

int nX = 2, nY = 3;
cout << nX + nY << endl;

C++ already knows how the plus operator (+)


should be applied to integer operands — the
compiler adds nX and nY together and returns the
result.
What would happen in this case?

Mystring cString1 = "Hello, ";


Mystring cString2 = "World!";
cout << cString1 + cString2 << endl;
• The intuitive expected result is that the string “Hello, World!” is
printed on the screen.
• However, because Mystring is a user-defined class, C++ does not
know what operator + should do.
• We need to tell it how the + operator should work with two objects
of type Mystring.
• Once an operator has been overloaded, C++ will call the appropriate
overloaded version of the operator based on parameter type.
• If you add two integers, the integer version of operator plus will be
called.
• If you add two Mystrings, the Mystring version of operator plus will
be called.
Operator Overloading

• Each individual operator must be overloaded for use with


user defined types.
– Overloading the assignment operator and the subtraction
operator does not overload the -= operator.
• Operator Overloading enables to apply standard operators
(such as +,-,*,<, and so on) to objects of the programmer
defined type. Function name
int a = b + c; operator+

int data type int data type


Returns an int
Calling Party Argument to function
Stored in a
L-Value R-Value , Called Party

14
Examples of already overloaded operators
• Operator << is both the stream-insertion operator and
the bitwise left-shift operator
• + and -, perform arithmetic on multiple types

• Overloading an operator
– Write function definition as normal
– Function name is keyword operator followed by the
symbol for the operator being overloaded
– Example : operator+ used to overload the addition
operator (+)
Operator Overloading

• What?
– an operator that has multiple meanings
– varies depending on use

• Why? Ease of use is a principle of OO

• How? by defining as an operator function


• functions that can extend meaning of built-in operators
(cannot define your own new operators)
• keyword operator is in definition, followed by the operator
to be overloaded

• Used
– method syntax or operator syntax
• s1.operator>(s2) vs. s1 > s2
C++ Operator Overloading
• Operator overloading refers to giving normal C++
operators such as +, *, and <= so on, an additional
meaning when they are applied to user defined data types
C++ Operator Overloading (Syntax)
returnType operator*(parameters);
↑ ↑ ↑
any type keyword operator symbol

■ Return type may be whatever the operator returns


■ Including a reference to the object of the operand

■ Operator symbol may be any valid operator


allowed by the language compiler (see the
following list)
Operators that can be overloaded
+ - * / % ^

& | ~ ! = <

> += -= *= /= %=

^= &= |= << >> >>=

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

|| ++ -- ->* , ->

[] () new delete new[] delete[]


18-01-2024 20
Cont..

18-01-2024 21
Types of Operators

OPERATORS
Deals with one Deals with two
argument arguments
Unary Binary
(+, <, =, …)

Prefix Postfix
(!, & , ~ , …) (++, --, …)
Restrictions on Operator Overloading
• First, at least one of the operands in any overloaded
operator must be a user-defined type.
• This means you can not overload the plus operator to
work with one integer and one double.
• However, you could overload the plus operator to work
with an integer and a Mystring.

• No overloading operators for built-in types


– Cannot change how two integers are added
– Produces a syntax error
Restrictions on Operator Overloading
• Overloading restrictions
– Precedence of an operator cannot be changed
– Associativity of an operator cannot be changed
– Arity (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
– For example, you could not create an operator ** to do
exponents.
The operator function can be defined either as

1. Member function
OR
2. Friend function (non member function)

Of the class which contains data members to be


operated by the operator.
Defined as member function
1. Defined outside the class then
Return type operator op (arg_list); (Declaration)
And
Return type class_name :: operator op (arg_list)
{ Objects
(definition)
of OperatorSpecify operands
this class is to
Function body…. symbol other than one
be operated +,_,*,/, etc being used to
} invoke this op
2.Defined inside the class
Return_type operator op (arg_list)
{…function body }
Important Note:
• A member function has no arguments for unary operators and
only one for binary operators.
• Because the object used to invoke the member function is
passed implicitly and therefore is available for member
function.
• A friend function will have one argument for unary operators
and two for binary.
• Arguments may be passed either by value or by reference in
case of friend function.
OVEROADING ARITHMETIC
OPERATORS
Overloading unary operator – (as
member function)
void show()
class space {
{ cout<<"x= "<<x<<" y= "<<y<<" z= "<<z;
int x; }
int y; void operator-()
int z; {
x=-x;
public: y=-y;
space() z=-z;
{ }
x=y=z=0; };
} void main()
space(int a, int b. int c) {
{ space s(3,-4,5);
x=a; s.show();
y=b; -s; // equivalent to s.operator-();
z=c; //s2=-s will not work because no value is returned
} s.show();
}
Note

• The function operator –() takes no argument.

• Since this function is a member function of the same


class, it can directly access the members of the object
which activated it.
Overloading unary operator – (as non-member
function)
void show()
class space
{
{
cout<<"x= "<<x<<" y= "<<y<<" z= "<<z;
int x;
}
int y;
friend void operator-(space &s);
int z;
};
void operator-(space &s)
public:
{
space()
s.x=-s.x;
{
s.y=-s.y;
x=y=z=0;
s.z=-s.z;
}
}
space(int a, int b, int c)
void main()
{
{
x=a;
space s(3,-4,5);
y=b;
s.show();
z=c;
-s; // equivalent to operator-(s);
}
// s2=-s will not work because no value is
//returned
s.show();
Note

• The argument is passed by reference.


• It will not work if we pass argument by value
because only a copy of object that activated the
call is passed to operator-().
• Therefore, the changes made inside the
operator function will not reflect in the called
object.
Overloading binary operator + (as
member function)
class complex complex complex::operator+(complex c)
{ {
int real; complex temp;
int imag; temp.real=real+c.real;
public: temp.imag=imag+c.imag;
complex() return temp;
{} }
complex(int r, int img)
{ void main()
real=r; {
imag=img; complex c1(3,4);
complex c2(5,6);
}
complex c3;
complex operator+(complex);
void show()
c1.show();
{
c2.show();
cout<<endl<<real<<"
c3=c1+c2; // equivalent to c3=c1.operator+(c2)
+j"<<imag;
c3.show();
}
}
};
Important Note
• Following features of this functions:
• 1. It receives only one complex type argument explicitly.
• 2. It returns a complex type value
• 3. It is a member function of complex.

• The function is expected to add two complex values and


return a complex value as the result but receive only one
value as argument. Where does the other value come
from?

Consider the statement


C3= C1+C2;
Code Explanation
• We know that a member function can be invoked
only by an object of the same class.
• Here the object:
– C1 take the responsibility of invoking the function
– 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
Code Explanation
• 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.
Implementation of the + overloaded
operator
Overloading binary operator + (as
non-member function)
class complex complex operator+(complex c1,complex c2)
{ {
int real; complex temp;
int imag; temp.real=c1.real+c2.real;
public: temp.imag=c2.imag+c2.imag;
complex() return temp;
{} }
complex(int r, int img)
{ void main()
real=r; {
imag=img; complex c1(3,4);
complex c2(5,6);
}
complex c3;
friend complex
operator+(complex,complex);
void show() c1.show();
{ c2.show();
c3=c1+c2; // equivalent to c3=operator+(c1,c2);
cout<<endl<<real<<" +j"<<imag;
c3.show();
}
}
};
Prefix increment Operator ++
Overloading
class Check { int main(){
private: int i; Check obj, obj1;
public: Check(): i(0)
{} obj.Display();
Check operator ++() { obj1.Display();
Check temp; obj1=++obj;
++i; obj.Display();
temp.i=i; obj1.Display();
return temp; return 0; }
}
void Display() {
cout<<"i="<<i<<endl; } };
Output:-

i=0
i=0
i=1
i=1
Postfix increment operator overloading
class Check {
private: int i; int main() {
public: Check(): i(0) Check obj, obj1;
{} obj.Display();
Check operator ++ (int)
{ obj1.Display();
Check temp; obj1=++obj;
temp.i=i++; obj.Display();
return temp; obj1.Display();
} obj1=obj++;
void Display() {
cout<<"i="<<i<<endl; } }; obj.Display();
obj1.Display();
return 0; }
Output:-

i=0
i=0
i=1
i=1
i=2
i=1
Assignment Operator overloading
Class sample Void operator = (sample obj) {
{ X= obj.x;
Private: Y= obj.y;}
Int x, y; Void display (){
Public: Cout<<”\n value of x”<<x;
sample(int a,int b) Cout<<”\n value of y”<<y;}};
{ main(){
X=a; Sample obj1(10,20), obj2(3,4);
Y=b; Obj2=ob1;
} Obj2.display();
}
==operator [ As a non-member
function]
int operator ==(sample &ob1, sample &ob2) { if(ob1.x
== ob2.x && ob1.y == ob2.y)
return1;
else
return(0);
}
Example:
Sample obj1(23,24);
Sample obj2(12,34);
If (obj1==obj2)
{cout<< “Equal”;} else{cout <<“Not equal”;
}
==operator [As a Member function
int operator ==(sample &ob2)
{ if(x == ob2.x && y == ob2.y)
return1;
else
return(0);
}
< operator [ As a non-member
function]
int operator < (sample &ob1, sample &ob2)
{ if(ob1.x< ob2.x && ob1.y < ob2.y)
return(1);
else
return(0); }
Class exercise
• Create a class called Distance with member
variables feet and inches. Give the required
constructor and getter and setter functions.
• a) Overload the unary minus operator. store the
result in a distance object.
• b)relational < operator to check whether dist1 is less
than dist2.
• c) binary + operator to add two distances
• d) overload the assignment operator
• e) overload the == operator.
• f)prefix increment and postfix increment operator.
Stream Extraction (<<) and Insertion
(>>)Operator
• The standard C++ library includes the header file iostream, where
the standard input and output stream objects are declared.
• The standard output of a program is the screen, and the C++ stream
object defined to access it is cout.
cout is used in conjunction with the extraction operator, which is
written as << (two "less than" signs).
1 .cout << "Output sentence";
2 .cout << 120;
3. cout << x;

• The << operator inserts the data that follows it into the stream
preceding it.
• In the examples above it inserted the constant string Output
sentence, the numerical constant 120 and variable x into the
standard output stream cout.
Stream Extraction (<<) and Insertion
(>>)Operator
• Standard Input (cin).
• The standard input device is usually the keyboard.
• Handling the standard input in C++ is done by applying the
overloaded operator of extraction (>>) on the cin stream.
• The operator must be followed by the variable that will store
the data that is going to be extracted from the stream. For
example:
1 int age;
2 cin >> age;
• The first statement declares a variable of type int called age,
and the second one waits for an input from cin (the keyboard)
in order to store it in this integer variable.
Overloading Stream-Insertion and
Stream-Extraction Operators

• Overloaded << and >> operators


– Overloaded to perform input/output for user-defined
types
– Left operand of types ostream & and istream &
– Must be a non-member function because left operand
is not an object of the class
– Must be a friend function to access private data
members
Overloading stream extraction( << )and
insertion (>>) operator for userdefined
data type
• Syntax
// ostream's insertion operator definition
ostream& operator<< (ostream& os, const Class& obj);

// istream's extraction operator definition


istream& operator>>(istream& is, Class &obj);
Program
• WAP that overloads the ostream and istream
operator using a non member function and
produces the following output:
Enter phone number in the form :
800 555 1212
The phone number entered was: (800)
555-1212
Example:-

class PhoneNumber
{
private:
string areaCode; // 3-digit area code
string exchange; // 3-digit exchange
string line; // 4-digit line
public:
friend ostream &operator<<( ostream &, const PhoneNumber & );
friend istream &operator>>( istream &, PhoneNumber & );
}; // end class PhoneNumber
ostream &operator<<( ostream &output, const PhoneNumber
&number )
{
output << "(" << number.areaCode << ") “<< number.exchange
<< "-" << number.line;
return output;
// enables cout << a << b << c;
}
istream &operator>>( istream &input, PhoneNumber
&number )
{
input >> setw( 3 ) >> number.areaCode; // input area code
input >> setw( 3 ) >> number.exchange;
// input exchange
input >> setw( 4 ) >> number.line; // input line
return input;
}
int main()
{
PhoneNumber phone; // create object phone
cout << "Enter phone number in the form :" << endl;

cin >> phone // invokes operator>> by implicitly issuing the global function
call operator>>( cin, phone )
cin >> phone;

cout << "The phone number entered was: “;

// cout << phone invokes operator<< by implicitly issuing


// the global function call operator<<( cout, phone )
cout << phone << endl;
return 0;
}

Output
Enter phone number in the form :
800 555 1212
The phone number entered was: (800) 555-1212
Class exercise

• Overload the Input


Output operator for the
Complex Class:
ostream& operator<<(ostream &os, const complex& c)
{ os << c.real << '+' << c.imag << 'i' << endl;
return os;
}

complex c1(3,5);
cout<<c1;

Output:-
3+5 i
Subscript operator[] overloading
const int SIZE = 10;
ArrayList::ArrayList()
class ArrayList
{ register int i;
{ private:
for(i = 0; i < SIZE; i++)
int arr[SIZE];
{ arr[i] = i; }
public:
}
ArrayList() ;
int &operator[](int i)
int main()
{ if( i > SIZE )
{ ArrayList A;
{ cout << "Index out of bounds"
<<endl; cout << "Value of A[2] : " << A[2]
<<endl;
// return first element. return arr[0];
cout << "Value of A[5] : " <<
} A[5]<<endl;
return arr[i]; cout << "Value of A[12] : " <<
} A[12]<<endl; return 0;
}; }
• Output:
Value of A[2] : 2
Value of A[5] : 5
Index out of bounds
Value of A[12] : 0
function call“ () operator overloading

• The function call


operator can take any
number of arguments of
any types and return
anything it wishes to.
class IntArray
{ private:
int *ptr;
public:
IntArray(int size) { ptr = new int[size]; }
~IntArray() { delete [] ptr; }
int& operator[](int index);
int& operator()(int index); };
//Function call operator
int& IntArray::operator()(int index){ return ptr[index];
}
int main(void)
{ IntArray iArray(10);
iArray(0) = 5;
• Output
iArray(1) = 3;
5
cout << iArray(0) << endl;
3
cout << iArray(1) << endl;
return 0; }
New and delete operator overloading
• Why overload new and
delete?
• To take charge or control
over how to allocate
memory
• To aid in debugging; keep
track of memory allocation
and deallocation in the
program
• To do some other operation
apart from allocating
memory at the time of
memory
allocation/decallocation
String Operator Overloading
class MyString friend MyString operator+(MyString obj1,MyString
{ obj2);
char *value; friend int operator==(MyString obj1,MyString obj2);
int len;
friend int operator!=(MyString obj1,MyString obj2);
public:
friend int operator<(MyString obj1,MyString obj2);
MyString()
{ friend int operator<=(MyString obj1,MyString obj2);
len=0; value=0; } friend int operator>(MyString obj1,MyString obj2)
friend int operator>=(MyString obj1,MyString obj2);
~MyString(){ } void display()
//String From Array {
MyString(char *s) if(len==0)
{ {
len=strlen(s); cout<<"\n String is Empty \n";
value=new char[len+1]; }
strcpy(value,s); else
} {
//String using Copy Constructor cout<<"\nThe result is:"<<value<<"\n";
MyString(MyString & s) }
{ }
len=s.len; };
value=new char[len+1];
strcpy(value,s.value);
}
MyString operator+(MyString obj1,MyString obj2)
{
MyString obj3;
obj3.len=obj1.len+obj2.len;
obj3.value=new char[obj3.len+1];
strcpy(obj3.value,obj1.value);
strcat(obj3.value,obj2.value);
return obj3;
}

Example:
Mystring str1(“Hello”);
MyString str2(“World”);
MyString str3;
Str3=str1+str2
• - HelloWorld
==Operator
int operator==(MyString obj1,MyString obj2)
{
int rel=0;
if(strcmp(obj1.value,obj2.value)==0){
rel=1;
}
return rel;
}
!=Operator
int operator!=(MyString obj1,MyString obj2)
{
int rel=0;
if(strcmp(obj1.value,obj2.value)!=0)
{
rel=1;
}
return rel;
}
int operator<(MyString obj1,MyString obj2)
{
int rel=0;
int result=0;
rel=strcmp(obj1.value,obj2.value);
if(rel<0) { result=1; }
return result;
}
>= Operator
int operator>=(MyString obj1,MyString obj2)
{
int rel=0;
int result=0;
rel=strcmp(obj1.value,obj2.value);
if(rel>0 || rel==0) { result=1; }
return result;
}

You might also like