from a tutorial

G

Guest

hey all,

i saw this example and had a question:

Imports System

Namespace MySpace

Public Class Foo : Inherits Bar

Dim x As Integer

Public Sub New()
MyBase.New()
x = 4
End Sub

Public Sub Add(x As Integer)
Me.x = Me.x + x
End Sub

Overrides Public Function GetNum() As Integer
Return x
End Function

End Class

End Namespace

' vbc /out:libraryvb.dll /t:library
' library.vb

Does this mean that if this class gets instantiated there will be 2 objects
because of the MyBase.New line? what would be the reasons for using the line
mybase.new?

thanks,
rodchar
 
L

Lucas Tam

Does this mean that if this class gets instantiated there will be 2
objects
because of the MyBase.New line? what would be the reasons for using
the line mybase.new?

No, one object. Mybase.new initializes the base class.
 
H

Herfried K. Wagner [MVP]

rodchar said:
Does this mean that if this class gets instantiated there will be 2
objects
because of the MyBase.New line? what would be the reasons for using the
line
mybase.new?

It's one object, but each instance of the derived class is an instance of
the base class too (inheritance /extends/ the base class, it adds something
to it). That's why the base class' constructor has to be called. There are
some situations where it's not necessary to explicitly call it -- in these
cases, the compiler will add the call to the base class' 'New' method.
 
C

Cor Ligthert

Rodchar,

Almost Lucas text with one little addition

No, one object. Mybase.new initializes the inherited part of the class.

I hope this helps?

Cor
 
D

David

It's one object, but each instance of the derived class is an instance of
the base class too (inheritance /extends/ the base class, it adds something
to it). That's why the base class' constructor has to be called. There are
some situations where it's not necessary to explicitly call it -- in these
cases, the compiler will add the call to the base class' 'New' method.

And in fact this is one of those times. If the call to MyBase.New were
deleted, the compiler would implicitly put it right back in anyway.
 
H

Herfried K. Wagner [MVP]

David said:
And in fact this is one of those times. If the call to MyBase.New were
deleted, the compiler would implicitly put it right back in anyway.

Yep. That's the case for parameterless constructors.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top