1

My objective is to test operator overloading by adding two objects of the same class. The member is a character array. In the main function, how to make the second line work

obj1="Hello "+obj2;

However, this works perfectly fine

myString obj1("Hello "),obj2("World");
obj1=obj1+obj2;

This is my class

//declaration of class
class myString
{
private:
    char the_string[50];
public:
    myString(); //constructor
    myString(char ch[]); //constructor overloading
    myString operator+(myString other_string); //+ overloading
    char* getdata();
};

Member function details:

//default constructor
myString::myString()
{
    the_string[0]='\0';
}

//overloaded constructor
myString::myString(char ch[])
{
    strcpy(the_string,ch);
}

//overloaded operator
myString myString::operator+(myString other_string)
{
    return myString(strcat(the_string,other_string.getdata()));
}

//printing result
char* myString::getdata()
{
    return the_string;
}

And finally, the main function:

//driver function
int main()
{
    myString obj1,obj2("World");
    obj1="Hello "+obj2; //the line that needs to work
    cout<<obj1.getdata();
    return 0;
}
GX_V
  • 9
  • 3
  • TL;DR of the dupe: `friend myString operator+(const char* lhs, const myString& rhs) { ... }` – NathanOliver Feb 24 '20 at 18:28
  • Define constructor taking `const char*` as a parameter and change your + function to `myString operator+(const myString& other_string) const` – Eric Feb 24 '20 at 18:30

0 Answers0