C++ Program to Check if Two Strings are Equal using Operator Overloading

In this program we are using the equality operator == to check if the given strings are equal or not. We have also written this program using Friend Functions.

C++ Program to Check if Two Strings are Equal using Operator Overloading

#include<conio.h>
#include<iostream.h>
#include<string.h>

class comp {
	public:
	char *s;
	void getstring(char *str)
	{
		strcpy(s,str);
	}

	void operator==(comp);
};

void comp::operator==(comp ob)
{
	if(strcmp(s,ob.s)==0)
		cout<<"\nStrings are Equal";
	else
		cout<<"\nStrings are not Equal";
}

void main()
{
	comp ob, ob1;
	char *string1, *string2;
	clrscr();

	cout<<"Enter First String:";
	cin>>string1;

	ob.getstring(string1);

	cout<<"\nEnter Second String:";
	cin>>string2;

	ob1.getstring(string2);

	//Call Equality Operator
	ob==ob1;
	getch();
}

C++ Program to Check if Two Strings are Equal using Operator Overloading with Friend Function

#include<conio.h>
#include<iostream.h>
#include<string.h>

class comp {
	public:
	char *s;
	void getstring(char *str)
	{
		strcpy(s,str);
	}

	void friend operator==(comp, comp);
};

void operator==(comp ob, comp ob1)
{
	if(strcmp(ob.s,ob1.s)==0)
		cout<<"\nStrings are Equal";
	else
		cout<<"\nStrings are not Equal";
}

void main()
{
	comp ob, ob1;
	char *string1, *string2;
	clrscr();

	cout<<"Enter First String:";
	cin>>string1;

	ob.getstring(string1);

	cout<<"\nEnter Second String:";
	cin>>string2;

	ob1.getstring(string2);

	//Call Equality Operator
	ob==ob1;
	getch();
}

You can notice the difference that in Friend Functions we need to pass two parameters in order to perform binary operations.

Output:
C++ Program to Check if Two Strings are Equal using Operator Overloading

Leave a Reply