SDF Operator Overloading
SDF Operator Overloading
Noida
SDF II (15B11CI211)
1
Objectives
• Overloading in C++
– Function overloading
– Operator overloading
• Different types of operators and their
overloading
• Operators that cannot be overloaded
C++ Overloading
Function Operator
int nX = 2, nY = 3;
cout << nX + nY << endl;
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
• 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
& | ~ ! = <
> += -= *= /= %=
|| ++ -- ->* , ->
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.
1. Member function
OR
2. Friend function (non member function)
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
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;
Output
Enter phone number in the form :
800 555 1212
The phone number entered was: (800) 555-1212
Class exercise
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
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;
}