Information Technology Reference
In-Depth Information
Virtual and Override Methods
In the previous section, you saw that when you access an object of a derived class by using a
reference to the base class, you get the members from the base class.
Virtual methods
allow
a reference to the base class, to access “up into” the derived class.
You can use a reference to a base class to call a method in the
derived class
, if the following
are true:
The method in the derived class and the method in the base class each have the same
signature and return type.
The method in the base class is labeled
virtual
.
The method in the derived class is labeled
override
.
For example, the following code shows the
virtual
and
override
modifiers on the meth-
ods in the base class and derived class.
class MyBaseClass // Base class
{
virtual public void Print()
↑
...
class MyDerivedClass : MyBaseClass // Derived class
{
override public void Print()
↑
Figure 7-8 illustrates this set of
virtual
and
override
methods. Notice how the behavior
differs from the previous case, where I used
new
to hide the base class members.
When the
Print
method is called by using the reference to the base class (
mybc
), the
method call is passed up to the
derived
class and executed, because of the following:
-
The method in the base class is marked as
virtual
.
There is a matching
override
method in the derived class.
-
Figure 7-8 illustrates this by showing the arrow coming out the back of the
virtual
Print
method and pointing at the
override
Print
method.
Figure 7-8.
Virtual method and an override method