Wednesday, November 15, 2023

Overloading Binary Operators

Binary operators are also used in overloading. They are also overloaded either using member functions or friend functions.

The member function requires one argument, whereas friend function requires two arguments because friend function is not a member function.

Syntax:-

returntype operator(classname)

{

-----------

}

 

Example. //Demonstrating binary operators in overloading

#include<iostream.h>

#include<conio.h>

class sample

{

private:

int n;

public:

sample()

{

 n=0;

}

sample(int k)

{

n=k;

}

void show(char *msg)

{

cout<<msg<<n<<endl;

}

sample operator+(sample s)

{

sample temp;

temp.n=n+s.n;

return temp;

}

sample operator-(sample s)

{

sample temp;

temp.n=n-s.n;

return temp;

}

sample operator*(sample s)

{

sample temp;

temp.n=n*s.n;

return temp;

}

};

void main()

{

clrscr();

sample s1(10),s2(20),s3;

s1.show("S1 : ");

s2.show("S2 : ");

s3=s1+s2;

s3.show("S1+S2 : ");

s3=s1-s2;

s3.show("S1-S2 : ");

s3=s1*s2;

s3.show(“S1*S2 : “);

getch();

}

0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top