Question

I have this Album class that I want to use as a Stack for a Song class.This is what I did so far:


const int intial_capacity=2; 
class Album
{
  Song* songs;
  char* name;
  int top;
  int capacity;
public:
 ...
};
bool Album::empty() const {
return top == -1;
}
bool Album::full() const {
return top == capacity - 1;
}
Song Album::pop() {
if (empty())
    return ???
return songs[top--];
}
Song Album::last() const {
if (empty())
    return ???
return songs[top];
}
bool ResizingStack::push(Song x) {
if (full())
resize();
songs[++top] = x;
return true;
}
void Album::resize() {
capacity *= 2;
int* newsongs = new Song[capacity];
for(int i = 0; i < capacity / 2; i++)
newsongs[i] = songs[i];
delete[] songs;
songs = newsongs;
}

I don't exactly know how to make my constructors and destructors so they can allocate memory correctly and don't give me crashes, also what should I return if Album is empty, it contains a compound type so I can't simply return 0 or '\0'. Any help is welcomed :)

Was it helpful?

Solution

You can use null object pattern. Define a (shared) null Song.

class Song {
public:
    static const Song null_song;
};

Song Album::pop() {
    if (empty())
        return Song::null_song;
    return songs[top--];
}

Remember to initialize Song::null_song.

OTHER TIPS

Essentially, it seems as if what you are trying to do boils down to implementing a stack.

There is already a standard library class template for that, std::stack, that you can use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top