Tip:
Highlight text to annotate it
X
A new method in a derived class can redefine a method in a base class in order to give
it a new implementation. To demonstrate we'll redefine Rectangle's getArea method by redeclaring
it in Triangle with the same signature. The signature includes the name, parameter list,
and return type of the method.
If we now create a Triangle and invoke the getArea method Triangle's version will get
called. However, if we upcast the Triangle to a Rectangle we will instead call Rectangle's
version. This is because the redefined method has only hidden the inherited method. That
is, Triangle's implementation is redefined downwards in the class hierarchy to any child
classes of Triangle, but not upwards to the base class.
In order to redefine a method upwards in the class hierarchy, what is called overriding,
the method needs to be declared with the virtual modifier in the base class. This modifier
simply allows the method to be overridden in derived classes. Calling the getArea method
from Rectangle's interface will now also invoke Triangle's implementation.
It is still possible to access a redefined method from a derived class by typing the
class name followed by the scope resolution operator. This is called base class scoping
and can be used to allow access to redefined methods that are any number of levels deep
in the class hierarchy.
Another place where this is important is in the constructors of derived classes. Base
class constructors in C++ are not implicitly called by derived constructors as they are
in C# and Java. Instead, they need to be explicitly invoked in the beginning of the derived constructor’s
initialization list in order to construct the base class. Note that we here don't have
to qualify the base constructor with the class name since this is implicit.