Reputation: 39
My professor gives us templates for programs and wants us to fill out the functions to the prototypes that he gives us, but I am having problems with how to properly return this Date function.
This is the Movie class, template, which instantiates a const Date releaseDate;
class Movie
{
public:
-->// all of "name(name), releaseDate(Date(yyyy, mm, dd)) {}" is what I added to the constructor, I think that is the only way I can
// properly instantiate Date because he said Date releaseDate must be constant.
Movie(string & name, int yyyy, int mm, int dd) : name(name), releaseDate(Date(yyyy, mm, dd)) {};
Date & getReleaseDate();
// other?
bool operator== (Movie &);
Movie & operator++();
friend ostream & operator<<(ostream &, Movie &);
friend ostream & operator<<(ostream &, const Movie &);
private:
Movie();
const Date releaseDate;
string name;
int rating;
};
and this is the Date class template
class Date
{
public:
Date(int, int, int);
//….
// other as appropriate
bool operator==(Date &);
friend ostream & operator<<(ostream &, const Date &);
private:
int day, month, year;
};
Then this is the overloaded << operator for Date that I believe should be correct
ostream & operator << (ostream & os, const Date & dt)
{
os << dt.month << "/" << dt.day << "/" << dt.year << "\n";
return os;
}
The only part I am having trouble with for the date, is how I call
Date & Movie::getReleaseDate()
{
cout << releaseDate;
return releaseDate;
}
it isn't giving me any errors for the cout << overloaded function, but since it says that getReleaseDate() must return something, I have to put in the return, but when I try to return releaseDate, it says "return: cannot convert from const Date to Date &" so what do I need to change to make this work? I am a little confused.
Upvotes: 2
Views: 74
Reputation: 17454
Having a const
member like releaseDate
limits you. Your class is no longer assignable, for example. Typically I would advise keeping your private data members non-const
— you can always expose a non-mutable public interface only.
You have to do that regardless. You cannot return a mutable reference to a const
thing. Your getReleaseDate()
should either return const Date&
or Date
(a copy).
Now, the function itself may as well be const
so that it works on a const Movie
.
It also shouldn't perform output; that's not "wrong" but it's unexpected and not what a user of your class would necessarily want. They can always do cout << movie.getReleaseDate()
if they want to do that.
Good job on your operator<<
.
Try to avoid the word "template" here. I know what you mean, but "template" means something specific in C++ and this isn't it.
Upvotes: 1