Sunday, August 2, 2009

/C++/ How do I use constructors in an array of objects?

Basic question. I have a class Song that has a constructor which defines the instance variables of it (title, artist, size). I want to make an array of Song objects with different constructor parameters for each; how would I do this?





Code snippets:





class Song


{


private:


string title;


string artist;


int size;





public:


Song(string aTitle, string aArtist, int aSize)


{


title = aTitle;


artist = aArtist;


size = aSize;


}











};





And I'm trying to make an array like so : Song songs[9];

/C++/ How do I use constructors in an array of objects?
I thinks in C++, if you need to make an array of objects.. you'll have to do OPERATOR OVERLOADING, which means that you'll have to define the meaning of using "[" and "]" with your new defined class.





This is an explanation of overloading "[]":


http://www.devarticles.com/c/a/Cplusplus...





*If you use C#, it's much easier... if you just wrote:





Song[9] = new Song();





it'll create an array of songs...
Reply:You could try rewriting Song. Add another parameter which is the index of the "songs" array you want to access. And instead of putting just "title = aTitle" you could replace that with " songs[index].title = aTitle ". Same goes for the artist and size. To be more specific:





Song(int index, string aTitle, string aArtist, int aSize)


{


songs[index].title = aTitle;


songs[index].artist = aArtist;


songs[index].size = aSize;


}





The code I did is basically the same. However, I used char instead of string.
Reply:Try this





Song SongArray[9] = { Song("Title One", "Artist One", 1), Song("Title Two", "Artist Two", 2), Song("Title Three", "Artist Three" 3), ...};





Normally, in defining an array the default constructor gets called.





You could also consider using a vector%26lt;Song%26gt;.





Then your code would look like


vector%26lt;Song%26gt; vecSong;





vecSong.push_back(Song("Title One", "Artist One", 1));


vecSong.push_back( Song("Title Two", "Artist Two", 2));


vecSong.push_back(Song("Title Three", "Artist Three" 3));


...


No comments:

Post a Comment