If a method declaration includes the Virtual modifier, this method is said to be a virtual method. Otherwise, the method is non-virtual.
The implementation of a non-virtual method is invariant relative to the type of object, for which the method is invoked. Implementation of a virtual method can be changed in derived classes. The process of changing the implementation of an inherited virtual method in a derived class is known as overriding that method.
In a virtual method invocation, the type of the instance, for which that invocation takes place is determined and the virtual method implementation is selected during the program runtime. In non-virtual method invocation, the compile-time type of the instance is the determining factor.
When a method named N is invoked with an argument list A on an instance with a compile-time type C and a runtime type R, the invocation is processed as follows:
First, overload resolution is applied to C, N, and A, to select a specific method M from the set of methods declared in and inherited by C.
If M is a non-virtual method, M is invoked.
Otherwise, if M is a virtual method, and the most derived implementation of M with respect to R is invoked.
For every virtual method declared in or inherited by a class, there exists a latest implementation of the method with respect to that class. The latest implementation of a virtual method M with respect to a class R is determined as follows:
If R contains the introducing declaration of virtual method M, this method is its latest implementation.
Otherwise, if R contains an override implementation of M, this is the latest implementation of method M.
Otherwise, the latest implementation of method M with respect to R is the same as the latest implementation of M with respect to the direct base class of R.
If implementation of the virtual method contains an expression of access to the basic member Inherited, the control is passed to the previous implementation of this method in one of parent classes. If the control passes to the virtual series by calling Inherited, the called method is determined relative to the class, in which implementation of the method, containing the Inherited call is declared.
Class A
Public Virtual Sub Test();
Begin
End Sub;
Public Sub Test1();
Begin
End Sub Test1;
End Class;
Class B: A
Public Override Sub Test();
Begin
End Sub;
Public Sub Run();
Begin
Inherited Test();
End Sub;
End Class;
Class C: B
Public Override Sub Test();
Begin
End Sub;
New Public Sub Test1();
Begin
End Sub Test1;
End Class;
Sub Main();
Var
p: C = New C();
Begin
p.Run(); // Call the B.Run method, which passes control to the A.Test method
(p As A).Test(); // Call of the last implementation of the Test - C.Test method
(p As A).Test1(); // A.Test1 method call
End Sub;
See also: