Virtual Methods

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:

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 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.

Example

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:

Methods | Access to Base Class