class DrawableObject
{
public:
virtualvoid Draw(GraphicalDrawingBoard&) const = 0; //draw to GraphicalDrawingBoard
};
class Triangle : public DrawableObject
{
public:
void Draw(GraphicalDrawingBoard&) const; //draw a triangle
};
class Rectangle : public DrawableObject
{
public:
void Draw(GraphicalDrawingBoard&) const; //draw a rectangle
};
class Circle : public DrawableObject
{
public:
void Draw(GraphicalDrawingBoard&) const; //draw a circle
};
typedef std::list<DrawableObject*> DrawableList;
DrawableList drawableList;
GraphicalDrawingBoard drawingBoard; //where GraphicalDrawingBoard is defined? why is this legal?
drawableList.pushback(new Triangle());
drawableList.pushback(new Rectangle());
drawableList.pushback(new Circle());
for(DrawableList::const_iterator iter = drawableList.begin(),
endIter = drawableList.end();
iter != endIter;
++iter)
{
DrawableObject *object = *iter;
object->Draw(drawingBoard);
}
after typedef std::list<DrawableObject*> DrawableList; the use of DrawableList and drawableList is confusing me, can someone explain to me please this part of the code?
Basically, with all three of those objects- Triangle, Circle, Rectangle- they all hold the function Draw in common. In other words, when the for loop iterates through the list of objects to call that specific function, it will do so for all three. This would normally not work if the function in the parent class was not abstract.
This would normally not work if the function in the parent class was not abstract.
This is not true. DrawableObject::Draw() is declared as virtual. This means that, even if DrawableObject::Draw() were defined, then the actual type of the object pointed to by a DrawableObject* will be correctly resolved at runtime, and if Draw() is overridden in the derived class, it will be called.
You don't need the base class method to be abstract, for polymorphism to work. The method just has to be virtual.
MikeyBoy do you mean that in the first time the loop runs, Triangle::Draw() will be called and the second time Rectangle and so on..? because this is what i think will happen.
MikeyBoy do you mean that in the first time the loop runs, Triangle::Draw() will be called and the second time Rectangle and so on..? because this is what i think will happen.
Yes, exactly. This happens because DrawableObject::Draw() is declared as virtual.
If DrawableObject::Draw()wasn't declared as virtual, then only DrawableObject::Draw() would be called. And, in this example, that's an abstract method, so doesn't exist.