C++ Program That Defines a Class String and Overload == Operator to Compare Two Strings [Operator Overloading Concept]

C++ Program That Defines a Class String and Overload == Operator to Compare Two Strings [Operator Overloading Concept]
#include<iostream>

#include<stdio.h>                             //used
for gets()

#include<string.h>                           //used for strcmp()

using namespace std;

class String

{

        char str[20];

        public:

        void
getdata()                            //function to read the string

        {

               
gets(str);

        }

        //operator
function to overload comparison operator and compare two strings

        int operator
==(String s)

        {

               
if(!strcmp(str,s.str))

                return
1;

                return
0;

        }

};

main()

{

        String s1,s2;

       
cout<<“Enter first string:”;

        s1.getdata();

       
cout<<“Enter second string:”;

        s2.getdata();

       
if(s1==s2)                                    //here
the operator function will be called

        {

               
cout<<“nStrigs are Equaln”;

        }

        else

        {

               
cout<<“nStrings are Not Equaln”;

        }

        return 0;

}

Explanation:

In this program we are creating a class String and with the help of the concept of operator overloading we
are comparing two strings. The class consists of a data member str to store string and a function getdata() to read value of str from user. It also contains an operator
function to overload == operator. The operator function take a class String type value as an argument and
compares two strings and return 1 when string are equal and 0 when they are
unequal.
I hope that you are able to understand the code. If you have
any doubt then you can ask it by commenting below. Happy Coding!

6 thoughts on “C++ Program That Defines a Class String and Overload == Operator to Compare Two Strings [Operator Overloading Concept]”

Leave a Comment

Your email address will not be published. Required fields are marked *