Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB4,VB5,VB6
Expertise: Intermediate
Apr 20, 1999

Passing Public class variables by reference

Under VB4 Public variables in form and class modules were implemented in the same manner as variables in BAS modules, that is, as direct references to memory locations. This allowed VB programmers to create procedures that modified values passed by reference, as in:


'--- the CInvoice class -----
Public Number As Integer

'---- elsewhere in the application
Dim p As New CInvoice
Increment p.Number     ' this works
Print p.Number         ' displays "1"

Sub Increment(value As Long)
    value = value + 1
End Sub
Under VB5 and VB6, Public variables in FRM, CLS and all other types of class modules (that is, all types of VB modules but BAS modules) are internally implemented as a pair of hidden Property Get and Property Let procedures. This means that, when such Public variables are passed as arguments of a procedure, what is actually passed is the return value of a procedure call. Hence, even if the Public property is passed with ByRef, the called procedure acts on a copy of its value, and therefore can't modify the value of the property.

This modified behavior fixes a problem of VB4, which didn't enforce a strict encapsulation of properties implemented as Public variables. However, when porting a program from VB4 to VB5 or VB6 you should pay attention to this issue, because the code might not work any longer. The only workaround is to move the property's value into a temporary variable, and pass such a temporary variable instead, as in:


Dim temp As Long
temp = p.Number
Increment temp
p.Number = temp
There are two other details to be aware of:

  • When the Public variable is passed to the external procedure from inside the class module, it is passed by reference, and therefore the procedure can change its value. In other words:
    
    ' inside the CInvoice class module
    Increment Number    ' it works!
    
  • On the other hand, if you use the Me prefix from inside the class module, the code will access the external property, and therefore the hidden property procedures. In other words:
    
    ' inside the CInvoice class module
    Increment Me.Number    ' it doesn't work!
    
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date