C++ Program For String Concatenation using Operator Overloading

Master C++ with Real-time Projects and Kickstart Your Career Start Now!!

Program 1

// Operator overloading (+ for string concat)
#include<iostream>
#include<string.h>
#define clrscr() system("cls")
using namespace std;
class TestString
{
    char str[500];
    public:
    TestString(char str[])
    {
        strcpy(this->str,str);
    }
    TestString()
    {}
    TestString operator+(TestString &k);
    void display();
};
void TestString::display()
{
    cout<<str;
}
TestString TestString ::operator+(TestString &k)
{
        TestString temp;
        strcpy(temp.str,str);    // temp.str="Hello"
        strcat(temp.str,k.str);// temp.str="Hello DataFlair"
        return temp;
}
int main()
{
    clrscr();
     TestString T1("This is Data Flair");
     TestString T2(" C++ Free Course");
     TestString T3;
     T3=T1+T2;  // T3=T1.operator+(T2);
      cout<<"\n";
      T1.display();
      cout<<"\n";
      T2.display();
      cout<<"\n";
      T3.display();


    return 0;
}

 

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

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