Rockford Lhotka
    CTO at Magenic
    Author, speaker, software architect
    Creator of the CSLA .NET framework

Home
Blog
CSLA .NET
Magenic
Speaking
Publications
About me
Contact me

Login

Simulating Inheritance in VB6

 

The ideal way (in my opinion) to simulate inheritance in VB6 is to use a combination of Implements and containment/delegation. However, I do recommend keeping the implementing interface methods as Private because their names are not exactly intuitive in my opinion. Thus, when I simulate inheritance I do so as follows.

Create a class named Parent:

Option Explicit

Public Sub DoSomething()
' do work here
End Sub

Public Sub DoOtherStuff()
' do work here
End Sub

This is our base class and has 2 methods that do useful work.

Now create a class named SubClass:

Option Explicit

Implements Parent

Private mobjParent As Parent

Private Sub Class_Initialize()
Set mobjParent = New Parent
End Sub

Private Sub Parent_DoOtherStuff()
DoOtherStuff
End Sub

Private Sub Parent_DoSomething()
DoSomething
End Sub

Public Sub DoSomething()
mobjParent.DoSomething
End Sub

Public Sub DoOtherStuff()
' do custom work here
mobjParent.DoOtherStuff
End Sub

Public Sub DoMyWork()
' do work here
End Sub

It implements DoSomething and DoOtherStuff on its native interface - It delegates those method calls back into a Private instance of Parent (using containment). In the case of DoOtherStuff it actually does some custom work before delegating the call - thus achieving the goal of inheritance that we can customize the behaviors of the base class if needed.

We also have extended the interface by adding the DoMyWork method - another key requirement of inheritance being that we can extend the interface.

Of course the 'interface' in this case isn't a formal interface it is the native interface on the SubClass - but via late binding we can now treat a SubClass object exactly like a Parent object.

For times when we want early binding this class Implements Parent. The elements of that interface are delegated to their native equivalents within SubClass - which means that they'll be overridden and/or delegated just like a call to the native method. This is nice because it means we have just one place to maintain the code - in the native methods for the SubClass class.

Obviously there are variations on this theme, but I believe this is basically what you were referring to in your email - and so you are absolutely correct, this combination of delegation and containment with the Implements keyword is the ideal solution for simulating inheritance.

Thankfully VB.NET actually provides us with inheritance so we can quit messing around with all this stuff in the relatively near future... 

(Updated 12/15/2000)