5.1.2 Virtual Generic Class Declaration


Through class inheritence, methods can be called with either the type of the inherited class or the type of the class that inherits it. A virtual method allows an inherited method to be overridden in some circumstances and not in others. This mechanism is required to allow inherited classes to be extended, yet allow the underlying methods to coexist with their extended counterparts.

When a method is inhertited from another class it can be overridden by a virtual method. This allows the a call to the method to invoke either the inherited method or the virtual method depending on the context. This is best explained by an example.


When Do.It is called and type of the the first argument is Minor, the version in the Major class is invoked. If the first argument has the type Minor the version in the Minor class is called. Other methods with a parameter whose type is Minor can receive arguments that are either Major or Minor types since Major inherits Minor.


The To.It method is declared Virtual in the Major class. When To.It is called and the type of the first argument is Major the version in the Major class is called, as is the case with the non-virtual method, Do.It. However, if the To.It method is called and the first argument is Minor, either version may be called depending on the context. In In the default context, the version in the Minor class is called.


The context changes when any method whose first parameter has the type Minor is called and the first argument passed in is Major. The context reverts back to the previous context after the call. Once the context has changed, if the To.It method is invoked with the Minor type, the version in the Major class is invoked instead.


Presumably, the variable passed to the virtual method is actually the same argument passed to the method that caused the context to change. If it was instead actually another variable with a Minor type, there would be problems. To help avoid this, virtual methods are generic and only the first parameter in a method may be passed to a virtual method. Still, virtual methods must be carefully applied. This can only cause problems in cases where an inherited class is extended with additional data structure fields.


Generic Class

Structure Type Declaration