String concatenation by operator overloading C++ -


i unable concatenate 2 strings operator overloading. code given below.

  #include<iostream>   #include<string.h>   using namespace std;   class string   {   char *len;   public:          string(char *s);          void display();          string(){}          void setdata(char *s);          //string(string &x);           ~string();           string operator+(string);          void extend(int l);             };    void string::extend(int f)    {        len=(char *)realloc(len,(f+1)*sizeof(char));    }         string string::operator+(string x)    {      string t;      printf("%s\n",len);      t.setdata(len);      t.extend(strlen(len)+strlen(x.len));      strcat(t.len,x.len);      printf("%s\n",t.len);      return (t);      }           string::~string()    {        delete len;        }                     void string::setdata(char *s)   {        len=(char *)calloc(strlen(s)+1,sizeof(char));       strcpy(len,s);    }         string::string(char *s)    {           len=(char *)calloc(strlen(s)+1,sizeof(char));                        strcpy(len,s);    }    void string::display()    {         printf("%s\n",len);     }   int main()   {      string a=string("united ");     string b,c;     b.setdata("states");     c=a+b;     c.display();     system("pause");     return 0;    }                                        

the problem string being concatenated inside operator overloading function when object returned , when display function invoked output garbage value.

your code doesn't follow rule of three. should manually overload copy-constructor , assignment operator. also, shouln't use delete on buffer, allocated malloc/calloc/realloc, use free instead.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -