It is not correct. To make it clearer, let me modify the example:
Code:
// You may not modify XTrackInfo
class XTrackInfo
{
std::string t_trackName;
int t_length;
public:
XTrackInfo();
XTrackInfo(std::string trackName, int tLength);
void setTrackName(std::string trackName);
void setTrackLength(int tLength);
const std::string& GetTrackName() const;
int GetTrackLength() const;
};
XTrackInfo::XTrackInfo() {}
XTrackInfo::XTrackInfo(std::string trackName, int tLength)
:t_trackName(trackName), t_length(tLength)
{}
const std::string &XTrackInfo::GetTrackName() const
{
return t_trackName;
}
int XTrackInfo::GetTrackLength() const
{
return t_length;
}
void XTrackInfo::setTrackLength(int tLength)
{
t_length = tLength;
}
void XTrackInfo::setTrackName(std::string trackName)
{
t_trackName = trackName;
}
class XMusicCd
{
private:
// You may not modify these member variables
std::string m_Author;
std::vector<XTrackInfo> m_TrackInfo;
public:
// You may not modify these member functions
XMusicCd();
XMusicCd(std::string Author, int mLength, std::vector<XTrackInfo> Tracks);
void SetAuthor(std::string Author);
const std::string& GetAuthor() const;
int GetLength() const;
void AddTrack(XTrackInfo NewTrack) {} // Left incomplete on purpose; you will implement it later
// Add additional functions to this class as necessary to make it compile.
};
void PrintCdContents(const XMusicCd& Cd)
{
// Implement this function such that it compiles
// Also, to be explicit, you may not add any tracks to the CD in here. That is not the purpose of this function. You may also not change the signature of the function.
// You shall specifically not modify the CD object by calling any setters.
}
int main()
{
// You may not change this function
XMusicCd MyCD;
PrintCdContents(Cd);
}
I want this code to compile. You may change the implementation of the class and the PrintCdContents, but not the main function.
This should force you to think about what functions a class should have, what information these functions need and where it comes from, and especially ownership of data.
This is a perfectly natural program and a perfectly natural interface that users of a class should come to expect. This is also probably what you would see when someone designs a class.
So what you should think about:
- Who owns data? The caller or the class itself? Does the class own the author or does the function the utilizes the class? Which makes more sense?
- What additional functions, if any, do you need to make the code work?
- What information does these functions need, if there needs to be added any, and where does it get that information from? What makes most sense?
Don't feel ashamed to ask for help if you're wondering something or get stuck. This is just an exercise, after all.
(I removed the SetLength and the total length member seeing as you incorporated the track into your design, so it should not be necessary anymore.)