You are on page 1of 10

1 EDais Basic classes tutorial

Basic introduction to classes in VB


Written by Mike D Sutton Of EDais Http://www.mvps.org/EDais/ EDais@mvps.org - 26.01.2002 -

Http://www.mvps.org/EDais/

2 EDais Basic classes tutorial

Introduction

Classes in VB

Im writing this tutorial as it seems to be a subject that numerous people find difficult to get to grips with at first which is a shame since knowing the advantages and disadvantages of different places to put your code can streamline and improve your application no end. I myself remember having difficulties grasping the idea of classes and it all only made sense after using other more pure-OO oriented languages such as Java and C++.

Http://www.mvps.org/EDais/

3 EDais Basic classes tutorial

Chapter I

Chapter 1

Ill start off with something everyone should be familiar with; a simple variable declaration:
Dim MyVar As Integer

Simple enough, weve all used it before. After a while however we find that the standard 8 or so VB variables dont cover all cases and in these cases this we can create our own type known as a User defined type or for short UDT. A UDT is simply a collection of the basic variables type that we can refer to as a single object. To create a UDT we must first create the Type declaration which tells VB what we want the type to contain; heres an example:
Private Type Person pName As String pAge As Integer pID As Long End Type

Once the type has been declared we can declare a variable of this new type as easily as one of the standard types:
Dim SomeGuy As Person

A single Person type can be passed round in exactly the same way as a variable and many unique instances of the type can be created simultaneously in the same way as we can create many Integer variables each with different values;
Dim PersonA As Person Dim PersonB As Person PersonA.pName = "Fredric" PersonA.pAge = 26 PersonB.pName = "Amanda" PersonB.pAge = 24 ' Displays: "Fredric is 2 years older than Amanda" Call MsgBox(PersonA.pName & " is " & PersonA.pAge PersonB.pAge & _ " years older than " & PersonB.pName)

Here you can see this visually, there's only one UDT declaration, but multiple instances of that UDT can be created from it based on the original template:

Http://www.mvps.org/EDais/

4 EDais Basic classes tutorial

Modules are used in VB mostly as a code repository where generic code is stored that is accessible application-wide. Modules are _not_ objects; theyre nothing more than a place to store code. A class module on the other hand _is_ an object and this is probably their biggest difference from standard modules. The best explanation I can think of for a class module for those who have never worked with them before is a cross between a form without a UI (User interface) and a UDT on steroids. Ive youve never used classes before then youre probably a little confused as to why exactly you should use them when you could just use UDTs or standard Modules in their place however hopefully after reading through this all should become clear or at least a little less hazy. Rather than trying to explain why to use a class and how their constructed and used, Ill take you through step by step of building a simple number class, and dont worry, as long as youve done a bit of programming before then its very unlikely youre going to find anything new in any code youll find here, the point here is the principle not the code. If youve not already fire up VB, start a new standard EXE project and add a new class module to the project from the project tree window or press Alt+P, C. Accept the default class module and you should now be looking at the blank code window of the class. Nothing difficult so far - it looks just like a standard module, lets see what this thing can do. The class we will build will be a simple number list structure that will be able to perform some basic mathematic functions like taking the mean/sum/min/max/range etc. As such well need an array to hold the numbers in, so add that to the class now:
Dim NumberList() As Integer

In this case were just declaring an empty dynamic array and well need some way of storing the number of numbers he have in the array so declare a variable to keep the count:
Dim NumNumbers As Long

These two variables will be in each instance of the class module, think of it like a UDT with the array and variable in. This is where things get different though, these variables are Private to the class instance and anything outside it cant view the variables without us specifically telling the outside world about their existence. A UDT is completely public and this is one of the nice things about the class, you can expose only as much of the internal workings as are needed, all the complexity is dealt with internally which makes writing complex object driven applications far easier and intuitive.

Http://www.mvps.org/EDais/

5 EDais Basic classes tutorial In this case however we do want the number of numbers stored within the class to be exposed as a property of the class like an element of the UDT, but heres another cool thing about classes we can make the property read only so the value can be read but not changed directly, this will be handled elsewhere in the class. To expose the property we create a little function known as a Property Get statement, which is nothing more than a simple function just with a fancy name.
Public Property Get NumCount() As Long NumCount = NumNumbers ' Return the number count End Property

The Get part means that the property can be read, if we wanted to make the property editable then wed need to put in a Property Let statement which Ill show you here for reference only, dont add it to the class:
Public Property Let NumCount(ByVal inNew As Long) NumNumbers = inNew ' Set the new number count End Property

Now well add the code to add a number to the array, Ill not bother explaining the code as such as its just basic VB, have a look in help for anything you may not have come across before.
Public Sub AddNum(ByVal inNum As Integer) ' Add a number ReDim Preserve NumberList(NumNumbers) As Integer NumberList(NumNumbers) = inNum NumNumbers = NumNumbers + 1 End Sub

This will re-declare the array, add our number into it and increment the counter. Before we give it a try, well add a function to remove all the numbers as well:
Public Sub Clear() ' Clear all numbers Erase NumberList NumNumbers = 0 End Sub

Finally name the class clsNum and then were ready to give it a spin. Go into the form code view and under form load well declare a new instance of it:
Dim MyClass As clsNum

Before we can use the class we have to tell VB to initialise it for us which is achieved using the Set keyword:
Set MyClass = New clsNum

However unlike standard variables we have to clear up the class instance when were done by setting it to nothing otherwise we can end up with memory leaks (Actually VB is very forgiving and will often clear it up for you, but its far better off to just destroy the class instance yourself so you know its memory has been released.)

Http://www.mvps.org/EDais/

6 EDais Basic classes tutorial Now we can use the class, if you type MyClass and hit the full stop key . youll see that theres three things been exposed, two are subroutines and one is a property, youll see if has a different icon to the others. Just as a quick test well add a couple of numbers to it and test the number counter to make sure its working so far:
Private Sub Form_Load() Dim MyClass As clsNum Set MyClass = New clsNum With MyClass Call MsgBox(.NumCount & " numbers") Call .AddNum(1) Call .AddNum(2) Call .AddNum(3) Call MsgBox(.NumCount & " numbers") Call .Clear Call MsgBox(.NumCount & " numbers") End With Set MyClass = Nothing End Sub

Now when you try running the code youll get 3 message boxs, the first will display 0 as its before weve added any numbers to the class, the second will display 3 as the class now had 3 numbers stored within it and the last will display 0 again after weve cleared the internal number list. This should demonstrate the basic object structure of classes and how to use them, however Id not blame you at the moment for scratching your head wondering why youd not just simply use an array instead. All will be revealed when we start adding more functionality to the class and getting it to do some more complicated stuff.

Http://www.mvps.org/EDais/

7 EDais Basic classes tutorial

Chapter II

Chapter 2

Ok, back to the class now and start a new public function called Sum that will return a Long. This will, surprisingly, take the sum of all the numbers in the internal array and return the answer:
Public Function Sum() As Long ' Return the sum Dim LoopNums As Long If (NumNumbers) Then For LoopNums = 0 To NumNumbers - 1 Sum = Sum + NumberList(LoopNums) Next LoopNums End If End Function

Again, nothing complicated there I hope. Since we have the Sum function written now, its dead easy to also add an average function that will take the mean of the number array which, in case you need brushing up on your mathematics, is calculated by taking the sum of all the numbers and dividing by the number of numbers. The cool thing here though is that we already have a sum function so we can just re-use that rather than having to re-write it all again and just adding a bit more functionality, we just need to add the Me keyword in front of it:
Public Function Mean() As Single ' Return the average If (NumNumbers) Then Mean = Me.Sum() / NumNumbers End Function

Now we can go back into the form and test the new version of the class. Add a call to the new Sum and Mean functions after the numbers have been added, but before the list is cleared:
Call MsgBox("Sum: " & .Sum()) Call MsgBox("Mean: " & .Mean())

The first call should return 6 which is all the numbers added together, and the second will return 2 which is the average of the numbers. Now you should be beginning to see the advantages of using a class over just a standard array, all the complexity is encapsulated within the class so all you ever see is the simple interface and the answer! But why stop there, lets add a few more functions to the class and give them a whirl too, heres Min and Max functions:
Public Function Min() As Integer ' Return the smallest number Dim LoopNums As Long If (NumNumbers) Then Min = NumberList(0) For LoopNums = 0 To NumNumbers - 1 If (NumberList(LoopNums) < Min) Then Min = NumberList(LoopNums) Next LoopNums End If End Function

Http://www.mvps.org/EDais/

8 EDais Basic classes tutorial


Public Function Max() As Integer ' Return the largest number Dim LoopNums As Long If (NumNumbers) Then Max = NumberList(0) For LoopNums = 0 To NumNumbers - 1 If (NumberList(LoopNums) > Max) Then Max = NumberList(LoopNums) Next LoopNums End If End Function

And again since weve already got these two written we can re-use them in conjunction with one another to find the range of the data also:
Public Function Range() As Long ' Return the range If (NumNumbers) Then Range = Me.Max() Me.Min() End Function

Now back in the form you can test out these new functions:
Call MsgBox("Minimum: " & .Min()) Call MsgBox("Maximum: " & .Max()) Call MsgBox("Range: " & .Range())

Which should return 1, 3, and 2 respectively for the minimum, maximum and range of the data. At this point though you may be thinking that classes are quite cool but they dont really seem to offer much of an advantage over standard code other than to keep it out of the way of the form, indeed you could easily accomplish what Ive shown you so far in a module or form. Now comes the real mind bender though; a class is not just a place to put code its an object and we can have as many instances of that same object as we want/need running simultaneously. To demonstrate this Ill create a new function called Clone that will clone the entire class and return us an exact copy of it as a new object! You can see here that in the same way as we had multiple instances of the UDT in the previous chapter that now we can have multiple instances of the class based on the original class template. Notice though that unlike the UDT, which was completely public, the class's internal code is inaccessible to the rest of the application unless specifically routed to through the public interface which is the only part that the rest of the application can see:

Http://www.mvps.org/EDais/

9 EDais Basic classes tutorial

The function itself is fairly basic so I wont go into it too much other than to say that it creates a new class instance and adds the numbers to it from the original one, theres nothing here that youve not seen before though:
Public Function Clone() As clsNum ' Create a clone Dim AddNums As Long Set Clone = New clsNum If (NumNumbers) Then For AddNums = 0 To NumNumbers - 1 Call Clone.AddNum(NumberList(AddNums)) Next AddNums End If End Function

Now, in the form we need to declare a new class instance for our cloned class:
Dim CloneClass As clsNum

Then we need to create the clone, this will go right after we test the mathematical functions of the original class, but before its cleared:
Set CloneClass = .Clone()

Notice that we use the Set keyword again, this is because were working with objects and not just standard variables. Now we can go to the end of the subroutine after the original class has been killed and youll see the data is preserved in the new class:
With CloneClass Call .AddNum(4) Call .AddNum(5) Call .AddNum(6) Call MsgBox("Clone count: " & .NumCount) Call MsgBox("Clone sum: " & .Sum()) Call MsgBox("Clone mean: " & .Mean()) Call MsgBox("Clone minimum: " & .Min()) Call MsgBox("Clone maximum: " & .Max()) Call MsgBox("Clone range: " & .Range()) End With Set CloneClass = Nothing

Http://www.mvps.org/EDais/

10 EDais Basic classes tutorial

Which will return 6, 21, 3.5, 1, 6 and 5 respectively for the count, sum, mean, minimum, maximum and range with the new three numbers as well as the initial three from the original class instance we cloned it from. Whilst this example class has no real use apart from as a demonstration many practical uses of classes include a database class that would encapsulate all the messy ADO or DAO (Or both!) code to manage record sets and databases, or an image class that would allow you to perform complex image manipulation through a single command to the object. Hopefully this has shown how classes can be very useful in programming and has outlined their differences from other code structures in VB. I hope this has been some use and if you were a little unsure of classes before that this has helped get your feet wet and to dispel some of the complexities surrounding classes. If you have any questions, comments or suggestions about this article then please, as always, feel free to contact me about it.

Edit log:
First written HTML conversion Uploaded Revision 2, HTML & PDF conversions 26/01/2002 27/01/2002 27/01/2002 13/03/2004

Mike D Sutton EDais 2004

Http://www.mvps.org/EDais/

You might also like