This operator
istream &operator>>(istream &stream, String obj) {
cout << "Enter a name: ";
stream >> obj.string;
return stream;
}
is invalid. Parameter String obj
is a local variable of the function that will be destroyed after exiting the function. Define the operator as
istream &operator>>(istream &stream, String &obj) {
cout << "Enter a name: ";
stream >> obj.string;
return stream;
}
Also define the output operator as
ostream &operator<<(ostream &stream, const String &obj) {
stream << obj.string;
return stream;
}
Take into account that it is not a good design of the class when data member string
is defined as public. Any body can change it.
class String {
int str_len;
public:
char *string;