Information Technology Reference
In-Depth Information
Using References to a Base Class
An instance of a derived class consists of an instance of the base class, plus the additional
members of the derived class. A reference to the derived class points to the whole class object,
including the base class part.
You can get a reference to the base class part of an object by casting an object reference, to
the type of the base class. In the next few sections you will look at accessing an object by using
a reference to the base class part of the object.
For example, in the following line of code, variable derived contains a reference to an
object of type MyDerivedClass . Figure 7-6 illustrates the parts of the object seen by the different
variables.
Casting the reference in derived to the type of the base class gives a reference to the base
class part of the object.
￿
The reference to the base class part is stored in variable mybc , on the left side of the
assignment operator.
￿
￿
The reference to the base class part cannot “see” the rest of the derived class object.
MyBaseClass mybc = (MyBaseClass) derived;
Figure 7-6. Different views of the same object through a reference to the derived class and a
reference to the base class
Search WWH ::




Custom Search