Your overloaded operator is a little broken (as the comments pointed out) but is unlikely to crash your program. There are many problems with this code that will crash it.
To start with, songs
is not initialized, which means that your songs[top]=p;
are actually storing the value of p to somewhere in the memory pointed to by stack garbage. That will likely crash your code. You are also not actually allocating storage space to store the songs
you added. Note that even if you initially allocated space to store one Song
, you can't just increment top
and store the next Song
; your addSong
will have to dynamically grow the allocated memory. Now, if you have a cap on the number of Songs an album can store, you can use the songs=new Song[MAX_SONGS]
approach suggested (and make addSong fail if the album hit its max capacity), but it's far better to use vector
s and string
s instead of pointers and raw new
s and delete
s if possible, and leave the memory management headache to the standard library. (You also didn't provide copy constructors and overloaded assignment operators; you would need both when your class does this sort of memory allocation, to prevent memory leaks and double deletion.)
Note that your constructor that takes a string is also broken; you haven't allocated any memory in name
at that point so there's nothing to delete.
Edit: To elaborate on my comment below, if you have to be able to handle arbitrary numbers of songs and you have to use new and delete, then your addSong
will have to do something like this (pseudocode):
void Album::addSong(Song& p)
{
new_size = size + 1;
new_songs = new Songs[new_size];
for( i = 0; i < size; i++)
new_songs[i] = songs[i];
new_songs[size] = p;
delete [] songs;
songs = new_songs;
size = new_size;
}
Your destructor will need to delete [] songs;
. Your constructor should set size to 0 and songs to the null pointer (it's legal to use delete on the null pointer; it has no effect).
You should also overload the assignment operator (which should first delete your own name and songs, allocate enough memory to hold the other album's name and songs, and copy them over) and the copy constructor (which should allocate enough memory to hold the other album's name and songs and then copy them over).