Talk:Polymorphism
Hi, I think there's a big conceptual error in the code examples: Almost all of them derive a Circle class from a Point class. This is IMHO conceptually wrong; derivation would mean that a circle is-a point, which is clearly not the case. You wouldn't normally pass circles to functions expecting points (say, a function returning the straight line through two points).
The task, as described, doesn't demand to make that error (although I suspect that whoever wrote that task had this wrong derivation in mind).
A conceptually clean implementation of the task could be (taking C++ as example):
#include <ostream> class Shape; { public: virtual void print(std::ostream& os) const = 0; }; std::ostream& operator<<(std::ostream& os, Shape const& s) { s.print(os); return os; } class Point: public Shape { public: Point(int x = 0, int y = 0); int x() const; int y() const; void print() const; private: int xpos, ypos; }; Point::Point(int x, int y): xpos(x), ypos(y) { } int Point::x() const { return xpos; } int Point::y() const { return ypos; } void Point::print(std::ostream& os) const { os << "Point(" << posx << ", " << posy << ")"; } class Circle: public Shape { public: Circle(Point const& c, int r); Point center() const; // Ok, not demanded by task, but makes sense int center_x() const; // not a good idea, but demanded by task int center_y() const; // dito int r(); void print(std::ostream& os); private: Point center; int radius; }; // etc.
Of course in that case it would make sense to add a few more functions to Shape (e.g. a move function, or a function returning a bounding box).