Re: dynamic_cast is ugly!
Nick Keighley wrote:
std::vector<Shape*> picture;
and you'd use a dynamic cast if you needed to know if a shape
was a Square (though why you'd need to know that...).
It's not really that you need dynamic cast to *know* if the shape is a
Square. In this case you need it if you want to *do* something to the
object if it's a Square, and this operation is not supported by Shape,
only by Square.
You could have two vectors:
std::vector<Square*> squares;
std::vector<Circle*> circles;
But then you lose their relative ordering. If you need to perform some
operations to all the shapes in order, you can't do it with only that
information.
You could have both:
std::vector<Shape*> picture;
std::vector<Square*> squares;
std::vector<Circle*> circles;
The pointers in 'picture' point to the same objects and the pointers
in the two other vectors. Now you can both directly access the Squares
and Circles, and you can perform something to all objects in order.
However, that's not good either. Now many operations become
exceedingly complicated. For example, removing the 5th shape in 'picture'.
Another problem is that if you need to perform an operation to all
Squares, but in the order in which they are in 'picture', it also
becomes complicated: Either you need to use dynamic_cast, or you need to
keep 'squares' in the same order as the pointers are in 'picture'. The
latter can be very complicated if the relative order of the shapes is
changed.