I tried to overload the +
operator on my own C styled
version of string
class.
Everything is fine except for the display()
call for the second string s2
which displays garbage values.
class string_ {
char *str;
int len;
public :
...
void display()
{
cout << str;
}
};
string_ :: string_()
{
str = 0;
len = 0;
}
string_ :: ~string_()
{
delete []str;
len = 0;
}
string_ :: string_(char *s,int l)
{
len = l + 1; // +1 for \0
str = new char[len];
int i;
for(i=0;i<len;i++)
str[i] = s[i];
str[i] = '\0';
}
string_ string_ :: operator +(string_ c)
{
int j = 0, i = 0;
string_ s;
s.len = len + c.len - 1;
s.str = new char[s.len];
while (str[i] != '\0')
{s.str[i] = str[i]; i++;}
while (c.str[j] != '\0')
{s.str[i] = c.str[j]; i++; j++; }
s.str[i] = '\0';
//The below statements gives the desired output
cout <<"\nIN operator +" << str;
cout <<"\nIN operator +" << c.str;
cout <<"\nIN operator +" << s.str;
return s;
}
int main()
{
char *str = "Hello";
char *str1 = " World";
string_ s1(str,5);
string_ s2(str1,6);
string_ s3 = s1 + s2;
cout << "\nstring s1 : ";
s1.display();
cout << "\nstring s2 : ";
s2.display(); //PROBLEM
cout << "\nConcatenated string : ";
s3.display();
return 0;
}