The example about the rectangle and triangle classes can be rewritten using pointers taking this feature into account:
|
| 20 10 |
Function
main
declares two pointers to Polygon
(named ppoly1
and ppoly2
). These are assigned the addresses ofrect
and trgl
, respectively, which are objects of type Rectangle
and Triangle
. Such assignments are valid, since both Rectangle
and Triangle
are classes derived from Polygon
.Dereferencing
ppoly1
and ppoly2
(with *ppoly1
and *ppoly2
) is valid and allows us to access the members of their pointed objects. For example, the following two statements would be equivalent in the previous example:
|
|
But because the type of
ppoly1
and ppoly2
is pointer to Polygon
(and not pointer to Rectangle
nor pointer toTriangle
), only the members inherited from Polygon
can be accessed, and not those of the derived classesRectangle
and Triangle
. That is why the program above accesses the area
members of both objects using rect
and trgl
directly, instead of the pointers; the pointers to the base class cannot access the area
members.Member
area
could have been accessed with the pointers to Polygon
if area
were a member of Polygon
instead of a member of its derived classes, but the problem is that Rectangle
and Triangle
implement different versions ofarea
, therefore there is not a single common version that could be implemented in the base class.
No comments:
Post a Comment