Professional Documents
Culture Documents
Operator Overloading SASTRA University C++ First Year
Operator Overloading SASTRA University C++ First Year
Operator Overloading SASTRA University C++ First Year
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() int main()
{ {
int a=10,b=20; int a=10,b=20;
++a; a++;
++b; b++;
cout<<a<<"\t"<<b; cout<<a<<"\t"<<b;
return 0; return 0;
} }
11 21 11 21
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() int main()
{ {
int a=10,b=20,x,y; int a=10,b=20,x,y;
x=++a; x=a++;
y=++b; y=b++;
cout<<x<<"\t"<<y<<endl; cout<<x<<"\t"<<y<<endl;
cout<<a<<"\t"<<b; cout<<a<<"\t"<<b;
return 0; return 0;
} }
11 21 10 20
11 21 11 21
1. Operator keyword
2. Operator arguments
3. Operator return values
}
Prefix increment (++) operator overloading
(Overloading + operator)
(Overloading + operator)
#include<iostream> else
using namespace std; return(a);
class comp }
{ };
public: int main()
int a; {
comp(int x) int s;
{ comp obj1(10);
a=x; comp obj2(20);
} s=obj1<obj2;
int operator <(comp c) cout<<s;
{ return 0;
if(a<c.a) }
return(c.a); 20
Overloading (<) comparison operator (Method 2)
Comparing Strings
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
return 0;
}
strcmp(str1, str2) = 32
strcmp(str2, str1) = -32
strcmp(str1, str3) =0
Overload string comparison (Method 1)
#include <iostream>
#include<string.h>
using namespace std;
class comp
{
public:
char str[20];
comp(char ss[])
{
strcpy(str,ss);
}
bool operator ==(comp y)
{
return(strcmp(str,y.str)==0)?true:false;
}
};
int main()
{
comp obj1("abcd");
comp obj2("abcd");
if(obj1==obj2)
cout<<"Strings are equal";
else
cout<<"Strings are not equal";
return 0;
}
Strings are equal
Overload string comparison (Method 2)
#include <iostream>
#include<string.h>
using namespace std;
class comp
{
public:
char str[20];
void getstring()
{
cout<<"Enter a string:";
cin>>str;
}
bool operator ==(comp y)
{
return(strcmp(str,y.str)==0)?true:false;
}
};
int main()
{
comp obj1,obj2;
obj1.getstring();
obj2.getstring();
if(obj1==obj2)
cout<<"Strings are equal";
else
cout<<"Strings are not equal";
return 0;
}
Enter a string: software
Enter a string: software
Strings are equal
Overload string comparison (Method 3)
#include <iostream>
#include<string.h>
#include <string>
using namespace std;
class comp
{
public:
string str;
comp(string h)
{
str=h;
}
bool operator ==(comp y)
{
return(strcmp(str.c_str(),y.str.c_str())==0)?true:false;
// strcmp is for C strings (null-terminated char *). string::compare is for C++ strings.
}
};
int main()
{
comp obj1("abcd");
comp obj2("abcd");
if(obj1==obj2)
cout<<"Strings are equal";
else
cout<<"Strings are not equal";
return 0;
}
Strings are equal
Overloading Arithmetic Assignment Operator
.* (Pointer-to-member Operator )