![]() ![]() | ||
By default, constructors are not inherited in Visual Basic. The idea here is that initializing a derived class's object will be different from initializing an object of the base class, so you're responsible for creating your own constructor in derived classes, if you want to give them one.
Tip |
Here's an important point-if you give a derived class a constructor, and the base class does not have an explicit constructor that you can call with no arguments, Visual Basic will insist that you call the base class's constructor first thing in the derived class. |
We saw an example of using constructors and inheritance in the Inheritance example on the CD-ROM, as discussed in the In Depth section of this chapter. In that case, I'm deriving the Dog class from the Animal class. The Animal class has a constructor that accepts a form, the main form for the program, and stores it in a protected member named MainForm. To pass that form from the Dog class's constructor back to the Animal class's constructor, I called the Animal class's constructor as MyBase.New (see the In Depth section of this chapter for more information):
Public Class Form1 Inherits System.Windows.Forms.Form 'Windows Form Designer generated code Dim spot As Dog Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click spot = New Dog(Me) spot.Breathing() End Sub End Class Public Class Animal Protected MainForm As Form1 Public Sub New(ByVal form1 As Form1) MainForm = form1 End Sub Public Sub Breathing() MainForm.TextBox1.Text = "Breathing..." End Sub End Class Public Class Dog Inherits Animal Public Sub New(ByVal form1 As Form1) MyBase.New(form1) End Sub Public Sub Barking() MyBase.MainForm.TextBox1.Text = "Barking..." End Sub End Class
Note that if you do call a base class's constructor from a derived class's constructor, that call must be the first line in the derived class's constructor.
![]() ![]() | ||