My program hangs when outputting contents of my linked list. I can't change the header, only the cpp file.
playlist.h:
class PlayList {
private:
struct SongNode {
Song data;
SongNode* next;
SongNode (const Song& s, SongNode* nxt = 0)
: data(s), next(nxt)
{}
};
friend std::ostream& operator<< (std::ostream& out, const PlayList& s);
SongNode* first; // head of a list of songs, ordered by title, then artist
//Snip...
inline
std::ostream& operator<< (std::ostream& out, const PlayList& pl)
{
for (PlayList::SongNode* current = pl.first; current != 0; current = current->next)
out << current->data << std::endl;
return out;
}
playlist.cpp
using namespace std;
PlayList::PlayList()
: totalTime(0,0,0)
{
}
void PlayList::operator+= (const Song& song)
{
SongNode* newNode = new SongNode(song, first);
first = newNode;
}
When outputting the list all of the data that is supposed to print, does print, but then the program hangs.
In the constructor of class PlayList, you need to initialise first:
public:
PlayList() : first(NULL) {}
Otherwise, in your operator<<, you reach the end of the list and instead of encountering NULL, you just get a junk pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With