I cannot see whats wrong with the codesnippet below where I try to overload the operator "=". I can build it but not run it (it crashes). Its due to the following syntax in the main method:
string2 = "my world!";
As far as I know - on the left handside of the operator is the object that holds the operator overloaded function and recevies the string-literal (that is passed to the function as an argument) on the right side of the operator.
below is the full code:
#include <iostream>
using namespace std;
class String {
public:
char *string;
String(char *ch) {
string = ch;
}
String (String &string_obj) {
string = string_obj.string;
}
String operator=(char *ch) {
strcpy(string, ch);
return *this;
}
};
ostream &operator<<(ostream &stream, String obj) {
stream << obj.string;
return stream;
}
int main() {
String string("hello ");
String string2(string);
cout << string << string2;
string2 = "my world!";
cout << string2;
return 0;
}