Subscribe Us

header ads

"+" Operator Overloading


Program to illustrate how to overload a "+" operator.

As we know that "+" operator or arithmetic operator can work only with predefined data types but here we use this arithmetic operator i.e. "+" operator for user-defined data types.

#include<iostream>
#include<string.h>
using namespace std;
class test
{
    char str[100];
    public:
    void getstr()
    {
    cout<<"Enter the string :"<<ends;
    cin>>str;
    }
    void show()
    {
        cout<<"String = "<<str;
    }
    test operator+(test s1);
};
int main()
{
    system("cls");
    test t1,t2,t3;
    t1.getstr();
    t2.getstr();
    t3=t1+t2;
    t3.show();
    return 0;
}
test test::operator+(test s1)
{
    test s2;
    strcpy(s2.str,str);
    strcat(s2.str," ");
    strcat(s2.str,s1.str);
    return s2;
}

Output :

Enter the string : suman
Enter the string : kumar
String = suman kumar





Post a Comment

0 Comments