Reputation: 70
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;
}
};
Upvotes: 0
Views: 103
Reputation: 34573
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.)
Upvotes: 6