• In my post “Overloading Binary Operator” I had showed you that how binary operators such as “+”, “-“,”*” can be overloaded. We had overloaded “+” operator for addition of two objects. We can also overload operators for string variables similar to objects. In this post, I am going to show you how to overload operators for string variable.
  • We know that we can create string either by array of character or by character type pointer. To perform any operation on string, (coping string from one string to another, joining two strings or string comparison) first we need to find out the length of a string and we have to perform operation character by character.
  • We can also use special in-built string function to perform operation on it but we cannot use over simple operators to perform operations on string. In C++ we can overload different operator to perform string operation as like as other number variable. Consider following class ‘String’ in which we are overloading + operator for joining two string into another one.
// Program to overload + and = operators for string data.

#include "iostream.h"
#include "conio.h"

class string
{
	char str[100];
	int len;
   
   public :
	void read();		// for reading string
	void print();		// for printing string
    // for overloading addition operator to joint two string
	string operator + (string);
   // for overloading equal to operator for equality of two string
        int operator == (string);
};

    // Function to read the string
void string :: read()
{
    cout << "Enter your string : " ;
    cin >> str;
    len=strlen(str) ;
}
   // Function to print the string
void string :: print()
{
    cout << "Your string is " << str << endl ;
}
  // Function definition for overloading + operator 
string string :: operator+(string s)
{
    string t;
    
    strcpy(t.str,str);
    strcat(t.str,s.str);
    
    t.len = len + s.len;
    
    return(t);
}
   // Definition for equal to operator
int string :: operator == (string s)
{
    if (strcmp(str,s.str)==0)
	return 1 ;
    else 
        return 0 ;
}
void main()
{
    clrscr();
    
    string s1,s2,s3;
    s1.read();
    s2.read();
  
    s3 = s1 + s2 ;  // call operator fucntion to join two strings.
   
    if(s1 == s2)   // call operator function to compare two strings.
	cout << “Both strings are same” <<endl ;
    else
	cout << “Both strings are different" <<endl ;
    
    s3.print();    // print string after joining.
    getch();
}
  • Similarly we can overload operators to compare two strings and for that we have to overload different relational operator like = = , <=, >=, !=, < , >.
  • We can also overload assignment operator “=” to copy one string into another but there is not need to overload assignment operator as object can directly assign to another object without overloading.