PART I
C h a p t e r 1 1 :
I n h e r i t a n c e
291
PART IPART I
// X references know only about X members
x2.a = 19; // OK
// x2.b = 27; // Error, X doesn't have a b member
}
}
In this program,
Y
is derived from
X
. Now, the assignment
x2 = y; // OK because Y is derived from X
is permissible because a base class reference,
x2
in this case, can refer to a derived class
object (which is the object referred to by
y
).
It is important to understand that it is the type of the reference variable—not the type of
the object that it refers to—that determines what members can be accessed. That is, when a
reference to a derived class object is assigned to a base class reference variable, you will
have access only to those parts of the object defined by the base class. This is why
Do'stlaringiz bilan baham: |