LessonInterface
class ILesson
{
public:
virtual void PrintLessonName() = 0;
virtual ~ILesson() {}
};
stl container
typedef list<ILesson> TLessonList;
calling code
for (TLessonList::const_iterator i = lessons.begin(); i != lessons.end(); i++)
{
i->PrintLessonName();
}
The error:
Description Resource Path Location Type passing ‘const ILesson’ as ‘this’ argument of ‘virtual void ILesson::PrintLessonName()’ discards qualifiers
You have to make PrinLessonName const.
Or not use a const_iterator, of course.
You want a list of pointers to ILesson's.
IMO, you'd also be considerably better off adding something like:
Then, instead of the loop you've written above, you can use something like:
As you can see, I've added one other minor embellishment in the process -- PrintLessonName takes a stream as its argument, instead of always printing to the same place. Of course, if you're not using streams, you may not want that...
Edit: Of course the other comments that you want to make PrintLessonPlan const are also correct...
You call a non-const method for a const object refered through a reference to const object.
Anyways:
I'm 100% sure you need to have a list of pointers:
in order to take advantage of polymorphism.
Having a list of values of ILesson is not possible, since ILesson is an abstract class.
Don't forget to delete the objects in the list of pointers, to avoid memory leaks.
PrintLessonName must be declared as const to be able to be called on const ILessons. Otherwise the compiler assumes it may modify the ILesson and prevents the call.
A version like this:
lessons.end() gets called once, and also note ++i instead of i++, which is faster (the post-increment operator involves creation of a temporary object, while the pre-increment doesn't).
People are correct about the lack of const. I'd favour using the for_each algorithm this will prevent calling lessons.end() for every entry.
Then use this: