0

I have a simple question.. Can i allocate and deallocate memory like this in the operator+ for other object

delete [] p.name; p.name = new char[strlen(a.name) + 1];

Look at the operator+

class PlDrustvo{
private:
   char *name;
public:
// Constructors and destructors are implemented.

PlDrustvo operator+(const PlDrustvo &a)
{
    PlDrustvo p(*this);
    if(///////){
        delete [] p.name;
        p.name = new char[strlen(a.name) + 1];
        strcpy(p.name, a.name);
    }

    return p;
}

};
  • 8
    Its legal. Your overloaded `operator +` is just like "any" other function. On a side note: Save yourself a lot of troubles, use `std::string`. – WhiZTiM Apr 02 '17 at 19:11
  • 1
    Yup. ^ if you are going this route anyway, here is an awesome set of answers that should help you out: [Operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading). Of particular interest is the trick sbi pulls with the += operator to make this really, really easy. – user4581301 Apr 02 '17 at 19:14
  • 1
    The function operator+ is a method like any other and there are no particular restrictions to what you "are allowed" to do inside it. Anyway, this implementation seems to copy rather than concatenete so it doesn't look like a vanilla +. –  Apr 02 '17 at 19:16
  • 1
    Yup, but please don't do this. You might want to look at unique_ptr or go with the line that Wyzard suggests. – Captain Giraffe Apr 02 '17 at 19:16
  • Thanks guys !! I'm using this just for experimentation and learning.. Sure I will look at recommended stuff !! Thank you again !! – Math Newbie Apr 02 '17 at 19:45
  • What happens if new fails and throws an exception? This is a complication that you might not want to worry about now. It is an issue that you should tackle at some point in your learning. Addressing it would dictate some changes to your code. – Avi Berger Apr 02 '17 at 20:58
  • @AviBerger Will take a note of that, thanks !! – Math Newbie Apr 03 '17 at 07:26

1 Answers1

6

Yes, you can do that. However, it's better to use std::string instead of char*. If name were a std::string, you could just write p.name = a.name; and it would allocate memory and copy the data automatically.

(std::string also has an operator+ that does string concatenation, so you could join the two names by writing p.name = name + a.name; – I'm guessing that might be what you actually want your operator+ function to do.)

Wyzard
  • 33,849
  • 3
  • 67
  • 87