I was trying to implement operator overloading to concatenate 2 strings but without using inbuilt string function and using pointers. The code is as follows:
#include<iostream>
using namespace std;
class str
{
public:
char* name;
str* operator+(str obj)
{
str obj3;
while(*name)
{
obj3.name = name++;
obj3.name++;
}
while(*obj.name)
{
obj3.name = obj.name++;
obj3.name++;
}
*(obj3.name) = '\0';
return &obj3;
}
};
int main()
{
str str1,str2;
str* str3;
str1.name = "hello";
str2.name = " there!";
str3 = str1+str2;
cout<<"the output is: "<<str3.name;
return 0;
}
I tried a lot of modifications but didn't succeed. All the solutions which I could find online were based on inbuilt string functions.
str str1; cout << str1.name;works properly. Then addstr str1("something"); str str2 = str1; str str3; str3 = str1;. (And never ever return a pointer to a local variable from a function. Ever.)