Programming and Graphics

(Kiana) #1

6.15 Pointers and virtual functions 189


Problems


6.14.1. Introduce the class of countries defined by the host continent, size,
population, and official language, and then define the derived class of
countries with two official languages.


6.14.2. Introduce the class of polygons defined by their vertices, and then
define the derived classes of triangles and quadrilaterals incorporating
respective functions that compute the area.


6.15 Pointers and virtual functions....................


In Section 6.10, we introduced pointers to class members. We can represent a
member of the flower class, F, and a member of the rose class, R, with pointers
that can be declared and initialized as:


flower * pointer = &F;

and


rose * pointer1 = &R;
flower * pointer2 = &R;

If we printpointer1andpointer2, they will be identical. This example illus-
trates that a pointer of a derived class is type-compatible with a pointer of its
base class.


However, the type-compatibility is a mixed blessing, as the statements:

pointer1 -> print();
pointer2 -> print();

arenotequivalent, even though the values of the two pointers are identical!
The first statement uses theprintfunction of the derived class, whereas the
second statement uses theprintfunction of the base class. The first statement
is equivalent to


R.print();

whereas the second statement cannot be implemented in terms of R. Thus, if
a flower pointer is issued for a rose, use of this pointer deprives us from using
rose functions whose names duplicate flower functions.

Free download pdf