Say I have a Person
class. This person class holds a Shape
.
The Shape
parent class has several child classes derived from it. For example Rectangle
and Circle
. Each of these child classes has their own methods. For example the Circle class has GetRadius()
, while the Rectangle class has GetWidth()
and more methods specific to that kind of shape.
Now let's say I have several people, some of which hold Rectangles and others hold Circles. I want to know what shape every person is holding and I want to get the information from those shapes. However I can't do this because the Person is holding a Shape, so it can't access any of the child specific methods.
I read something about casting but I found it to be a bit confusing and I was not sure whether or not casting would be the best way to do this, or whether there is a more efficiënt way to go about this entirely. So how could I do this?
Edit 1: Edit for more clarification.
I want the methods such as GetWidth()
and GetRadius()
to return different types.
virtual
keyword. In such a case, you would have to call the functions that provide informationGetRadius()
andGetWidth()
the same name in each child class e.ggetShapeInfo()
.getShapeInfo()
would also be defined in Shape. You would probably makegetShapeInfo()
a pure virtual function. MeaningShape
is a abstract class. This is because, there exists no shape in the world, only things of a shape type, like a circle. – izaak_pyzaakShape
and eachPerson
would have aShape *s
to allow dynamic binding, then when either theCircle
orRect
is pointed too callings->getShapeInfo()
will call either the circle or rectangle function, depending on the type of the object pointed to bys
– izaak_pyzaakgetShapeInfo()
fromCircle
would return the radius in double, however I would like to have thegetShapeInfo()
fromRectangle
to return something like avec2
holding the width and height. – JohnCakeShapeInfo
that returns from both. Although, this is somewhat shifting the problem of reflection onto a new type, to make the function call look neater. But you don't know who will hold what shape, this may be the way to go. Was the thing you read about casting about the dangers of down casting? Ultimately if you have two distinct functions and callgetRadius
on a rectangle, bad things will ensue. – izaak_pyzaak