0

I new to programming and study about operator overloading. To overload "+" to add two string. But when I try to combine two string using strcpy, the second string replace the first string instead of copy with first string.

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

using namespace std;

class String
{
    char str[100];
public:
    void operator +(String);
     String()
     {
         strcpy(str,"");
     }
     String(char a[100])
     {
         strcpy(str,a);

     }

};

void String::operator+ (String str1)
{ char temp[100];
  strcpy(temp,str);
  strcpy(temp,str1.str);
  cout<<temp;
}
int main()
{
    String s1=String("Hello");;
    String s2=String("World");
    s1+s2;


    return 0;
}

Output

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103

2 Answers2

1

The error in your code is that In the operator overloading function you should use strcat - string concatenation For more info check out : String concatenation

joseph kalathil
  • 196
  • 1
  • 2
  • 10
0

I think you've missed to assign the value of the two strings to a new string like this:

String nString = s1 + s2;