AIM: Write a program to Overload Unary and Binary Operators as Member Function, and Non Member Function.
Unary operator as member function.
AIM: Write a C++ program to overload unary operator as member function.
THEORY:
The unary operators operate on a single operand and following are the examples of Unary operators −
- The increment (++) and decrement (–) operators.
- The unary minus (-) operator.
- The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as post-fix as well like obj++ or obj–.
SOURCE CODE:
#include<iostream>
using namespace std;
class num
{
private:
int a,b,c;
public:
num(int j,int k,int m)
{
a=j;b=k;c=m;
}
void show(void);
void operator ++( );
};
void num::show()
{
cout<<“\n a= “<<a<<“\n b= “<<b<<“\n c= “<<c;
}
void num::operator ++( )
{
++a;
++b;
++c;
}
int main()
{
num n(13,63,241);
n.show();
++n;
n.show();
}
OUTPUT:
a=14
b=64
c=242
ii. Binary operator as nonmember function.
AIM: Write a C++ program to illustrate binary operator as a non-member function.
THEORY:
A binary operator is an operator that operates on two operands and manipulates them to return a result. Operators are represented by special characters or by keywords and provide an easy way to compare numerical values or character strings.
Binary operators are presented in the form:
Operand1 Operator Operand2
SOURCE CODE:
#include<iostream>
using namespace std;
class FBOP
{
int x,y;
public:
FBOP(){ }
FBOP(int a,int b)
{
x=a;
y=b;
}
void show()
{
cout<<“x= “<<x<<“\t y= “<<y<<endl;
}
friend FBOP operator+(FBOP ob1,FBOP ob2);
};
FBOP operator+(FBOP ob1,FBOP ob2)
{
FBOP temp;
temp.x=ob1.x+ob2.x;
temp.y=ob1.y+ob2.y;
return temp;
}
int main()
{
int a,b;
cout<<“Enter first object values:\n”;
cin>>a>>b;
FBOP ob1(a,b);
cout<<“Enter second object values:\n”;
cin>>a>>b;
FBOP ob2(a,b),ob3;
ob3=ob1+ob2;
cout<<“Values of first object are:\n”;
ob1.show();
cout<<“Values of second object are:\n”;
ob2.show();
cout<<“Addition of two objects is:\n”;
ob3.show();
}
OUTPUT:
Enter first object values:
12 36
Enter second object values:
42 15
Values of first object are:
x=12 y=36
Values of second object are:
x=42 y=15
Addition of two objects is:
x=54 y=51