I have the following code, in which I dynamically allocate memory, and then it deletes it two times in the destructor, causing an error. How can I go about fixing this?
(Nothing wrong, see edit below).
class Song {
private:
char *name;
public:
Song (char *name = "") {
this->name = new char[strlen(name)+1];
this->name[strlen(name)] = '\0';
strcpy(this->name, name);
}
~Song() {
cout << "DEST" << endl; // gets called 2 times, causing an error.
delete [] this->name;
}
};
class CD {
private:
Song songs[1];
public:
CD() {}
~CD() {}
};
int main() {
CD cd1;
Song song1("Song1");
return 0;
}
Edit: It seems like this code doesn't actually have anything wrong.
The problem was in another part of my code: I used the = operator, but didn't have a copy assignment constructor. Thanks for your help suggesting the rule of three.