On 20.03.2016 12:01, Jens Kallup wrote:
> Hello,
That's what President Obama also said at the start, in his yearly speech
to the Iranians, now two or three days ago.
> How can I create a C++ structure of classes:
>
> Shape
> |
> PositionOfShape
> / \
> Rectangle Circle
> \ /
> Properties
> - Color
> - Brush...
Nice but misleading ASCII artwork. The connecting lines denote quite
different forms of relationship, as I see it. For presumably a Rectangle
IS a Shape, for example, while a Shape HAS a Position, or HAS a Color.
This is one basic thing you need to be careful with, and keep in mind
that beginners have a tendency to incorrectly model HAS as IS.
Essentially then,
Shape
HAS a position
HAS a line color
HAS a background brush
Rectangle IS a Shape
Circle IS a Shape
Next you need to think hard about whether such objects are pure VALUES
or MUTABLE (objects whose values can be modified).
If they are pure values, like numbers, then a Circle can be a kind of
Ellipse, because it has all the properties of an Ellipse. It's just a
subset of ellipses. The other way doesn't work, because it's not the
case that every Ellipse or most Ellipses has exactly one radius.
But if they are mutable, then if a Circle were derived from Ellipse then
one could presumably use some modifier function of Ellipse to make that
Circle elongated, decidedly un-Circle like. And thus breaking the class
invariant of Circle. And so with mutable objects it's impractical to
derive Circle from Ellipse. Instead one can offer conversions between
these classes. A conversion from Circle to Ellipse will always succeed
except for e.g. memory exhaustion.
> I think each class (Rectangle, and Circle) have same standard
> properties. Can i specialize it in sub class?
A derived class is a specialization. It is also an extension.
> Like radius of Circle, and radius of borders circle (as example)?
If you're talking about radius of borders then that doesn't sound very
reasonable.
> Is it possible to iterate through Shape to know how many objects are present?
If you put these objects in a collection, yes.
Cheers & hth.,
- Alf