OPERATOR
OVERLOADING :
- The mechanism of giving such special meaning to an operator is known as operator overloading.
- Operator overloading provides flexible options for the creation of new definitions for most of the c++ operators accept the following:
1] class member access operator(.)
2] scope resolution operator(::)
3] size of operator(size of)
4] condition operator or ternary
operator(?:)
- It is used to perform operation on the user-defined data type.
Example for operator overloading :
- Overload an operator '+' in a class like string to concatenate two strings using +.
Advantages of operator overloading :
- Enables programmers to use notation closer to target domin.
- Provides similar syntactic support to user-defined types.
- It makes the program easier to understand.
Rules for operator overloading :
- Cannot overload overloading data type.
- Arity of operators cannot be changed.
- Precedence of operators remains same.
- Only build-in operators can be overloaded.
Overloading Unary Operators:
class
unary
{
int a;
public:
void getdata()
{
cout<<"Enter
number";
cin>>a;
}
void display()
{
cout<<a;
}
void operator_()
{
a=-a;
}
};
void
main()
{
unary ob1;
ob1.getdata();
ob1.display();
-obz;
obz.display();
}
Operator
Overloading : Increment
Class
increment
{
int a;
public;
void getdata()
{
cout<<”Enter
Number”;
cin>>a;
}
void display()
{
cout<<a;
}
void operator ++()
{
a=++a;
}
};
void
main()
{
increment ob1;
ob1.getdata();
ob1.diaplay();
++ob1;
ob1.display();
ob1++;
ob1.display();
}
Slip 2
Operator
Overloading : Decrement
Class
decrement
{
int a;
public;
void getdata()
{
cout<<”Enter
Number”;
cin>>a;
}
void display()
{
cout<<a;
}
void operator --()
{
a=--a;
}
};
void
main()
{
increment ob1;
ob1.getdata();
ob1.diaplay();
--ob1;
ob1.display();
ob1--;
ob1.display();
}
Slip 3
Binary
Operator Overloading
Class
binary
{
int a,b;
public;
void getdata()
{
cout<<”Enter
Number”;
cin>>a>>b;
}
void display()
{
cout<<a<<b;
}
void operator +(binary ob1)
{
binary ob2;
ob2.a=a+ob1.a;
ob2.b=b+ob1.b;
return ob2;
}
};
void
main()
{
binary b1,b2,b3 ;
b1.getdata();
b2.getdata();
b3=b1+b2
b3.display();
}
Slip 4
Relational
Operator Overloading
Class
relational
{
int a;
public;
void getdata()
{
cout<<”Enter
Number”;
cin>>a;
}
void display()
{
cout<<”a=”<<a;;
}
int operator>(Relational r)
{
if(a>r.a)
{
Return 1;
}
Else
{
Return 0;
}
}
};
void main()
{
Relational r1,r2;
r1.getdata();
r2.diaplay();
if(r1>r2);
{
r1.display();
cout<<”r1 is
greater”;
}
else
{
r2.display();
cout<<”r2 is
greater”;
}
}
Comments
Post a Comment
If you have any doubts. Please let me know.