0

Here I wrote 2 overloaded operators:

stringb operator+(const stringb &a,const stringb &b)
{
    stringb temp;
    temp.len = a.len + b.len;
    temp.p=new char[(temp.len)+1];
    strcpy(temp.p, a.p);
    strcat(temp.p, b.p);
    return (temp);
}
stringb operator-(const stringb &a,const stringb &b)
{
    stringb temp;
    temp.len=a.len-b.len;
    temp.p=new char[temp.len+1];
    strcpy(temp.p,a.p);
    return (temp);
}

However, when I compile the actual code, the whole code works except the part when I call these operator, and I get garbage out put. What's wrong with my functions?

EDIT: Declaration of stringb class:

class stringb
{
    public:
        char *p;
int len;
public:
    stringb()
    {
    len=0;
    p=0;
    }
stringb(const char *s)
{
    len=strlen(s);
    p=new char[len+1];
    strcpy(p,s);

}
stringb(const stringb &s)
{
    len=s.len;//strlen(s);
    p=new char[len+1];
    strcpy(p,s.p);
}
~stringb()
{
    delete p;
}

friend int operator==(const stringb &a,const stringb &b);
friend stringb operator+(const stringb &a,const stringb &b);
friend stringb operator-(const stringb &a,const stringb &b);
friend void putstring(const stringb a);

};
Anurupa_Dey
  • 113
  • 4
  • 11

2 Answers2

2

Your problem is here:

~stringb()
{
    delete p; // <<<<<
}

This will be executed if temp goes out of scope in your operator definition.

To get your code working you need a proper implementation of the Rule of Three in your stringb class. You may also have a look at this nice IDE one sample, P0W has setup from your code.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • No! You'll need to implement proper rule of 3 in `stringb` – πάντα ῥεῖ Nov 23 '13 at 16:18
  • Here's a good explanation and example: [Wikipedia 'Rule of three'](http://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29) – πάντα ῥεῖ Nov 23 '13 at 16:33
  • 1
    SO's contribution http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three – john Nov 23 '13 at 16:35
  • @Anurupa_Dey See it [your](http://ideone.com/0EjAoQ) implementation and **Rule of Three** – P0W Nov 23 '13 at 16:48
  • @g-makulik You should add "rule of three" statement into your answer – P0W Nov 23 '13 at 16:50
  • 1
    @g-makulik I don't think the OP understands your answer. Maybe walking him through what would cause his code to crash and why? I would respond, but you're answer is correct. I just don't think he is familiar enough with the Rule of Three. Just a thought, great answer by the way. – Freddy Nov 23 '13 at 17:13
0

Try returning a reference:

stringb& operator+(const stringb &a, const stringb &b);
{
   stringb *temp = new stringb();
   temp->len = a.len + b.len;
   [...]
   return *(temp);
}
Eutherpy
  • 4,471
  • 7
  • 40
  • 64