First time writing here. I've seen several other questions like mine, but couldn't solve my problem. I have 4 classes : Song, Playlist, Album, Artist. Playlist consist of array of songs. Album inherits Playlist and has some more functuality and Artist consist of array of Albums and some other stuff.
Album(char* _name, Song* songs,int _sales ,int _year,int n):Playlist(songs,n)
{
name = new char[strlen(_name)+1];
strcpy(name,_name);
salesCount=_sales;
year = _year;
};
Playlist::Playlist(Song* _songlist, int n)
{
if(n > 20)
{
cout<<"The number of song must be lesser or equal to 20"<<endl;
return;
}
SongList = new Song[n];
for(int i = 0 ; i<n; i++)
{
SongList[i] = _songlist[i];
}
numberOfSongs=n;
}
When I create an Album using this constructor I don't have anyproblems, but when I try to create an Array of albums , that consists of album created with this construtor I get a memory access violation. Any Ideas ?
Ok so I updated my code a little bit. Here is what I'm trying to do in the main method:
Song newSong("My Song", 9, 231),mySong("Your Song", 8 , 180),yourSong("His Song",7,135), herSong("Her Song",8,431);
Song songs[4] = {newSong, mySong,yourSong,herSong};
Album yourAlbum("My Album",songs,200000, 2010, 4);
yourAlbum.PrintInfo(); //<------- WORKS
Album albums[1]; //<------ It calls the deffault constructor of Album and after it gives me //"Source not available"
//When I try to declare it like this Album albums[1] = { yourAlbum } ; it gives me access violation
Artist myArtist("blake", albums);
myArtist.PrintArtistInfo();
Playlist::Playlist(Song* _songlist) {
numberOfSongs = sizeof(*_songlist)/sizeof(_songlist); // <-- THIS
...
leads to unexpected (nonsense) value being assigned to the numberOfSongs
since it is equal to:
numberOfSongs = sizeof(Song) / sizeof(Song*);
In case you need your function to know the size of the dynamically allocated array, you should keep track of this size on your own and pass it to this function.
Also note that since you are programming in C++, you should use features that this language provides,. You should use std::string
instead of C-style strings and STL containers such as std::vector
instead of C-style arrays (in case of std::vector
, the object internally holds the information about its length, so you wouldn't be dealing with this kind of problems).