Saksham
Saksham

Reputation: 9380

Operator overloading to concatenate string

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.

Upvotes: 0

Views: 3818

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258548

Well, things that stand out immediately are:

  • there's no clear ownership of the name member - in your case, you set it to some string literals, but what if you allocate it with new? Who's responsible for destruction then? Who's the owner?
  • operator+ returns a pointer to str, not a str, so str3 = str1+str2; is invalid.
  • str obj3; never has its member initialized, but you try to write in it, which is undefined behavior.
  • passing by value will create copies, which is bad if you don't follow the rule of three- which in this case isn't even clear if you need.

Upvotes: 3

Related Questions