x2
can’t
access
b
even when it refers to a
Y
object. This makes sense because the base class has no
knowledge of what a derived class adds to it. This is why the last line of code in the program
is commented out.
Although the preceding discussion may seem a bit esoteric, it has some important
practical applications. One is described here. The other is discussed later in this chapter,
when virtual methods are covered.
An important place where derived class references are assigned to base class variables
is when constructors are called in a class hierarchy. As you know, it is common for a class
to define a constructor that takes an object of its class as a parameter. This allows the class to
construct a copy of an object. Classes derived from such a class can take advantage of this
feature. For example, consider the following versions of
Do'stlaringiz bilan baham: |