1

I have a base class and derived class, the base class has two methods which are overridden in the derived class. Let's take the following scenario:

My base class

public class BaseClass

public Overridable function method1()

method2()
End Function

public Overridable function method2()
' Empty !!!
End Function
End class 

My Derived class

public class DerivedClass

public Overrides function method1()

MyBase.method1()
End Function

public Overrides function method2()

' Some code !!
End Function
End class 

Now I have created an instance of the derived class and call method1().

Dim obj as new DerivedClass()
obj.method1()

method1() in the derived calls method1() in the base, which calls method2 in the base. the strange thing to me that method2 in base, which is empty, called the method2 in the derived! ..

Can any one explain to me what is happening and how calling methods with inheritance done? and what concept was applied with this hierarchy ?

Areej Qadomi
  • 143
  • 1
  • 1
  • 14

2 Answers2

1

method1() in the derived calls method1() in the base, which calls method2 in the base.

This is where you are wrong.

Since method2 is overridable, it is a "virtual method". Thus, all calls to method2 call the overridden version. This includes the method2 invocation in method1 of the base class:

Public Class BaseClass
    Public Overridable function method1()
        method2()  ' <-- If method2 has been overridden, the overridden
                   '     version is called here.
    End Function
    ...
End Class
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • You mean that any Empty overridable method is a "Virtual Method" ? How does the compiler knows that the overridden method should be executed instead of the Empty method ? – Areej Qadomi May 10 '17 at 12:27
  • @AreejQadomi: *Every* overridable method (not just empty ones) are "virtual methods". The compiler does not know it. The *runtime* knows that the concrete type of your object is "DerivedClass" and, thus, its implementation of method2 must be called. For that reason, this is called "*run-time* polymorphism". – Heinzi May 10 '17 at 13:17
1

Overridable methods in VB, like virtual methods in C#, are not called directly but typically employ what is called a vtable which contains pointers to methods. In this way when you have an instance of type BaseClass the vtable will point to the BaseClass version of the overridable method. When you have an instance of DerivedClass a pointer to its version of the method overwrites what was in the vtable and so when the method is invoked it will call the derived class version. For more information on vtables see this question

Community
  • 1
  • 1
Steve Ellinger
  • 3,957
  • 21
  • 19