Results 1 to 19 of 19

Thread: [RESOLVED] Classes

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Sep 2006
    Posts
    236

    Resolved [RESOLVED] Classes

    I'm relatively new to VB6 though I've been programming since about 1970 - the vast majority in machine code and assembly. Higher level languages are fairly new to me but I want to learn some new tricks. I've been reading about classes (mostly from teaching myself C++) and was really confused about it for awhile ... but I think the light bulb just went off. Tell me if I've got the jist of things ...

    I'm working on a baseball game in VB6. Each game has two teams, of course, with up to 30 players per team. It occurred to me that each player could be considered to be a class. (?) Each player has a team, name, batting preference, defensive rating, position and throwing arm among other variables. Pitchers have those and others so perhaps a pitcher class as well? So far I've been using arrays to define the variables, but would I be better off creating a separate class for each player? Is doing so a more efficient use of memory or would it make the program run faster?

    I've got more questions, but I wanted to be sure I'm understanding what a class is first. Since I'm just learning, I don't want to develop bad habits and want my code to be as efficient as possible.

    TIA,
    Ken

  2. #2
    Addicted Member
    Join Date
    Jul 2007
    Posts
    228

    Re: Classes

    My first thought would be to create a User Defined Type rather than a Class. But I could be wrong. Are you familiar with Types?

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Sep 2006
    Posts
    236

    Re: Classes

    Thanks for your reply, Tom. No ... I had thought a type was something like integer, long, double, string, etc.

  4. #4
    Addicted Member
    Join Date
    Jul 2007
    Posts
    228

    Re: Classes

    Well... kind of. A small example of a UDT
    Code:
    Type EmployeeRecord   ' Create user-defined type.
       ID As Integer   ' Define elements of data type.
       Name As String * 20
       Address As String * 30
       Phone As Long
       HireDate As Date
    End Type
    
    Sub CreateRecord()
       Dim MyRecord As EmployeeRecord   ' Declare variable.
    
       ' Assignment to EmployeeRecord variable must occur in a procedure.
       MyRecord.ID = 12003   ' Assign a value to an element.
    End Sub
    It would seem to me you could do the same with Players and Pitchers.

  5. #5
    Junior Member
    Join Date
    Feb 2008
    Location
    Stockholm / Sweden
    Posts
    22

    Re: Classes

    Tom is right, you've just realized that you want UTD's without knowing it yet!
    Let me try and give you a closer example.

    vb Code:
    1. ' Keep adding variables for more complex teams
    2. Type TeamStats
    3.     Name as String
    4.     Batting as Integer
    5.     DefRating as Integer
    6.     Position as Integer
    7.     ThrowArm as Integer
    8. End Type
    9.  
    10. ' this will generate 5 teams
    11. Dim Team(4) as TeamStats
    12.  
    13. 'Put everything above this bar in your general declarations window
    14. --------------------------------------------------------------------------
    15.  
    16. ' this is a way to preset the start values of each team unless you want all teams at 0 by default
    17. Team(0).Name = "USA"
    18. Team(0).Batting = 5
    19. Team(0).DefRating = 2
    20. Team(0).Position = 10
    21. Team(0).ThrowArm = 3
    22.  
    23. Team(1).Name = "Canada"
    24. Team(1).Batting = 3
    25. Team(1).DefRating = 5
    26. Team(1).Position = 8
    27. Team(1).ThrowArm = 2
    28.  
    29. 'etc...
    Put that in a sub called LoadTeams and take it from there. Play around with it until you understand it.
    Last edited by Tr4iNe3r; Feb 13th, 2009 at 12:39 AM.

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    Sep 2006
    Posts
    236

    Re: Classes

    OK .. I see. Thank you both! A User defined type then is sort of like a container for related data. I'm basing everything on individual players as opposed to teams, but each player could be named and based on that name I could bring up all the various attributes that particular player has using a . (dot) somewhat in the same way as a control uses me.txtTextbox.

    Now when I'm done using each individual type (each player say) to clear them can I use some sort of destructor like set player(x)=nothing or a loop setting player(x) = "" ? or must I clear each contained variable? Like at the end of a game, when I'm intending to begin another in the same iteration of the program.

    And one more question if I may ... since this all started with my "revelation" about classes - what would be the difference between a user defined type and a class? They seem similar but then I'm not really sure I grasp what a class is.

    Thanks very much guys!

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Sep 2006
    Posts
    236

    Post Re: Classes

    OK ... I was just fiddling around with this a bit. I can see one problem that comes up right off and that is keeping the players separated in a more meaningful way than by their place in an array. If I use an array for each UDT then I would have to remember each of 60 numbers to keep the players straight in my head. There are 2 teams each with 30 players. For example ...

    Code:
    PlayerStats as Type
         Name as string
         Rating as integer
    End Type
    
    Dim Player(60) as PlayerStats
    Now I have 60 instances of PlayerStats each with a unique name (Player(0) - Player(60)). The confusion would come from wanting the defensive rating of Bob Jones who happens to be 37 in the array of 60. Wouldn't I have to know Player(37).Rating in order to return that individual piece of data? That is going to end up being much more confusing than my present individual variable method as I would have to know the player number of each player. A UDT would be much more useful if I could refer to the UDT simply as "Bob Jones" or Player="Bob Jones". Can this be done with a UDT?

    Thanks,
    Ken

  8. #8
    Cumbrian Milk's Avatar
    Join Date
    Jan 2007
    Location
    0xDEADBEEF
    Posts
    2,448

    Re: Classes

    A UDT provides a way of grouping several variables together under one name. Generally speaking a UDT is handled just like any other variable. UDT's can be nested i.e. one of a UDT's subtypes could be another UDT.

    A Class describes an object. A Class can be used in a similar way to a UDT but it can also do a lot more, eg have it's own methods properties etc. A Form is a class.

    Here is an example of how you could (but wouldn't) define a team as an object
    Code:
    Option Explicit
    
    Public Name As String
    Public Batting As Integer
    Public DefRating As Integer
    Public Position As Integer
    
    Private cThrowArm As Integer
    
    Public Property Get ThrowArm() As Integer
        ThrowArm = cThrowArm
    End Property
    
    Public Property Let ThrowArm(value As Integer)
        If value > 80 Then
            value = 80
        ElseIf value < 10 Then
            value = 10
        End If
        cThrowArm = value
    End Property
    
    Private Sub Class_Initialize()
        Debug.Print "I'm alive!"
    End Sub
    
    Private Sub Class_Terminate()
        Debug.Print "Bye!"
    End Sub
    ...and how you might then use it...
    Code:
    Option Explicit
    Private mTeams() As cTeam
    
    Private Sub Form_Load()
        ReDim mTeams(3)
        Set mTeams(0) = New cTeam 'creates a new instance of the class
        
        With mTeams(0)
           .Name = "thing"
           .DefRating = 32
           .ThrowArm = 99
        End With
        
        Set mTeams(1) = mTeams(0) 'creates a second reference the 1st team
        
        Debug.Print mTeams(1).DefRating
        Debug.Print mTeams(1).ThrowArm
    
        set mteams(1) = nothing 'destroys said reference
    End Sub
    Note how Throwarm has some restrictions as to what values can be set to it.

    Classes are a lot slower than UDT's but much more powerful.
    Last edited by Milk; Feb 13th, 2009 at 07:50 AM.

  9. #9
    Cumbrian Milk's Avatar
    Join Date
    Jan 2007
    Location
    0xDEADBEEF
    Posts
    2,448

    Re: Classes

    Quote Originally Posted by SparrowHawk7
    A UDT would be much more useful if I could refer to the UDT simply as "Bob Jones" or Player="Bob Jones". Can this be done with a UDT?
    You could use a collection instead of an array.

  10. #10
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Classes

    That isn't an issue with a UDT, that is an issue with arrays - and I'm afraid it can't be done (it could with a Collection, but that can't hold UDT's ).

    However, it doesn't really matter much, as all that counts is being able to find the data, which you would need to do whether or not you used UDT's.

    One way to do that would be to loop the array and compare the name to what you want (which you could put into a function to save repeating it), and a better way is to not use the names in the code - just use the numbers instead. That would save memory, make it faster, and avoid problems that would otherwise be caused if two or more players have the same name.



    Oh, and in relation to the thread title/your original question, a Class is basically an extended version of a UDT - in addition to having the variables (or "properties") it can also contain code (to check the values are within a certain range, etc).



    edit: I took far too long writing this, Milk managed to get two replies in while I was writing!

  11. #11
    Cumbrian Milk's Avatar
    Join Date
    Jan 2007
    Location
    0xDEADBEEF
    Posts
    2,448

    Re: Classes

    Quote Originally Posted by si_the_geek
    edit: I took far too long writing this, Milk managed to get two replies in while I was writing!
    you might be pleased to hear I wrote that first reply in notepad first. Thankfully you also point out that Collections can't hold UDT's.

  12. #12

    Thread Starter
    Addicted Member
    Join Date
    Sep 2006
    Posts
    236

    Resolved Re: Classes

    Thanks so much guys! I just now started to look into collections but that opens an entirely new can of worms so I'll put that off till a bit later when I can digest the MSDN explanations.

    Milk - thanks for the sample class code - since I'll never need to do any work within the team class a UDT is more reasonable. I would suspect then, that if I wanted to open a document within the program from time to time (such as a data report in it's own form say), doing that as a class might make sense.

    I can see that using a class for each player type is a bit overkill - a UDT will suffice as I only have about 10 things to keep track of for any player and about 21 for each pitcher. However, the UDT would only be used as a container for keeping those individual pieces of information together (they don't change) - I'm not manipulating that data so a class would be much more than I would need. I'm working with a database that contains all that information for each of 900 individual players - 30 teams of 30 players each. Each player is indexed with an autonumber ID so it would be easy to use that to identify each player. but I only need 60 of them at a time for the game - 30 on each team.

    Would this work? Say I made a UDT and set each one in an array Player(0-59)
    Code:
     x=0 
         Do until Player(x).name = "Bob Jones"
         x=x+1
         loop
    
    'x now contains the index of the UDT I want
    I haven't tried this but they seem like it'd work. Would it be possible to use a SQL statement to locate the UDT that I wanted? That would be simplest but I don't understand enough of SQL to see how it would be done.

    Is it possible to array the UDT by the player name? ... there are only 60 of them so memory allocation shouldn't be a problem.

    This is an aside question - once upon a time I seem to recall being able to enlarge the samples in MSDN by using the wheel in conjunction with CTRL or something. After a reload, I added the mouse wheel fix to the addins of VB6 but I cannot figure out how to enlarge the print in the examples. Maybe my memory is poor, but is there some way to use the mouse wheel to enlarge the print in there? The examples are SOOO small. Sometimes I have to copy and paste them into a word processor document to be able to see them.

    Sorry to be a pain ... (it's kinda my nature I suppose ... I'm the curious sort) I like to be sure I really understand something before moving on - things have a nasty way of building on one another and if I don't get something understood that's at the bottom, the rest is then built on a house of cards.

    I hope all this was coherent ... I'm repairing 2 computers (my job) and intermittently talking to customers and clients on the phone as I write this ...

    Ken
    Last edited by SparrowHawk7; Feb 13th, 2009 at 12:13 PM.

  13. #13
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Classes

    Quote Originally Posted by SparrowHawk7
    Would this work? Say I made a UDT and set each one in an array Player(0-59)
    Code:
     x=0 
         Do until Player(x).name = "Bob Jones"
         x=x+1
         loop
    
    'x now contains the index of the UDT I want
    It would usually work, with two exceptions.

    The first would create an error, which is when the item you are looking for is not found in the array (as you will try to access an array element that doesn't exist). You need to exit the loop if x is bigger than the UBound (and then not run the rest of the code, and probably show a message to the user).

    The second exception would cause a bug, and is something I briefly mentioned before - if a case ever occurs where two players have the same name, at some point searching by name will give you the wrong player. Unless you have a good reason to do otherwise, I would recommend searching by something that is guaranteed to be unique - such as the AutoNumber from the database.

    I haven't tried this but they seem like it'd work. Would it be possible to use a SQL statement to locate the UDT that I wanted? That would be simplest but I don't understand enough of SQL to see how it would be done.
    You cannot use SQL on arrays (whether they are UDT's or other data types), only on databases of some kind.

    Is it possible to array the UDT by the player name? ... there are only 60 of them so memory allocation shouldn't be a problem.
    I'm not sure what you meant by that, but as above I would recommend not focussing on the name.

    This is an aside question - once upon a time I seem to recall being able to enlarge the samples in MSDN by using the wheel in conjunction with CTRL or something. ...
    I just checked, and you need to use the menu, "View"->"Fonts"

    Sorry to be a pain ... (it's kinda my nature I suppose ... I'm the curious sort) I like to be sure I really understand something before moving on - things have a nasty way of building on one another and if I don't get something understood that's at the bottom, the rest is then built on a house of cards.
    Don't be sorry about that - it's the opposite that annoys people.

  14. #14

    Thread Starter
    Addicted Member
    Join Date
    Sep 2006
    Posts
    236

    Re: Classes

    Quote Originally Posted by si_the_geek
    You cannot use SQL on arrays (whether they are UDT's or other data types), only on databases of some kind.
    Yeah I thought about that after I pushed submit ... duh.

    I just checked, and you need to use the menu, "View"->"Fonts"
    That did the trick .. the little things you don't think to check, huh?

    Thanks to all you guys for helping me to understand something new. Next comes collections ... (I'll probably be back with more questions!)

    Ken

  15. #15
    Junior Member
    Join Date
    Feb 2008
    Location
    Stockholm / Sweden
    Posts
    22

    Re: [RESOLVED] Classes

    Since no one mentioned the use of Enum's which is short for "Enumerations", i would like to give you one more option before you move on to collections because there is a simple solution to make "your" code less confusing by using them. I personally can't stop using them.

    vb Code:
    1. ' you can of course make it public if needed
    2. Private Enum Teams
    3.     USA = 0
    4.     CANADA = 1
    5.     MEXICO = 2
    6.     ARGENTINA = 3
    7. End Enum
    8.  
    9. ' An example of how to use it
    10. Private Sub Test(WhichTeam As Teams)
    11.  
    12. Select Case WhichTeam
    13.     Case USA
    14.         MsgBox "USA Triggered!"
    15.     Case CANADA
    16.    
    17.     Case MEXICO
    18.    
    19.     Case ARGENTINA
    20.      
    21. End Select
    22.  
    23. End Sub
    24.  
    25. ----------- put the above in the general declarations -------------
    26.  
    27. ' this is how to trigger the event
    28. Call Test(USA) ' type this and you will get a list of your Enum's

    All the team names actually represent a number, so USA is translated into the number 0 and so on. An important note is that you can actually use numbers when you make cases so you dont have to make a case for each team e.g Case 0 to 3.

  16. #16

    Thread Starter
    Addicted Member
    Join Date
    Sep 2006
    Posts
    236

    Re: [RESOLVED] Classes

    Thanks for the tip Tr4iNe3r. Interestingly I got to fiddling with enums yesterday while experimenting with stuff in VB. I was sort of looking for a "container" for information and thought an enum would be useful. It seems to be rather like a collection except that it only holds 1 type of variable in a numerical order while a collection can hold nearly anything. My attempts to force a collection to hold a UDT didn't work but I can see that would be a collection of sorts within another collection. An enum is more straightforward.

    There seem to be quite a few options for holding/grouping data in VB which is why there are so many different ways to approach any problem. Often several are legitimate with no one necessarily being better or worse than another. Other times there are clear advantages to one over another.

    My background is such that I am quite comfortable with UDTs as they are what I have always used but in an indirect way. I'd set aside memory to hold data in consecutive order and then a master matrix as pointers to each individual piece of data in the block and offset an accumulator to point to a specific location within that matrix I wanted. Much like a collection as well. I can also relate to enums that way. I suppose it's very like learning a foreign language ... you tend to always translate stuff into your old familiar language until you learn to think in the new one. I'm just learning to think in VB with some C++ tossed in for seasoning but I tend to try to figure out what's happening within the memory locations and at the core of the processors. Once I get a handle on that in my head I can understand more of the command and hopefully how it can be used. I still tend to concentrate on efficiency. When I first started programming I had 48K of memory to work with plus some zero page locations (about 8 bytes which was enough) in an 8 bit architecture. It's amazing what you can actually do with 48K if you are a good memory steward. I do kind of miss using bits as flags but I don't think VB is very useful that way. Course, you don't need to worry so much about memory usage these days either.

  17. #17
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: [RESOLVED] Classes

    An Enum is just a modification of the Long data type - you can use constants that you define rather than numbers, and get a drop-down list for them in the code window. There is an article in the FAQs that explains enums in more detail.

    It's not just storing data that has multiple options, pretty much anything in VB can be done in a variety of ways!

  18. #18

    Thread Starter
    Addicted Member
    Join Date
    Sep 2006
    Posts
    236

    Re: [RESOLVED] Classes

    Thanks Si ... I have read some of the articles/examples you kindly give in your signature - I'm working my way through them. Slowly things seem to sink in but I sometimes need concrete examples that I can relate to in order for things to gel in my head and that often takes more time. But anything worth learning takes time. I've been a professional musician before as well as currently being an artist and know very well how it all basically boils down to practice, practice, practice. (as well as experiment and try new stuff). So I post what are probably dumb questions here when I get confused and you folks kindly bear with me while I sort things through. Like I said in an earlier post, I like to get a good solid foundation of understanding before I go to build on it too far. That way I don't ask (too many!) stupid questions.

    Thanks for bearing with me ...
    Ken

  19. #19
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: [RESOLVED] Classes

    Learning anything properly takes time, and we all have our preferred ways of doing it. Your ways are similar to most of us here (and are not rude at all, such as the "write it all for me!" that some people try), so we have no problem there.

    As yet I don't think I've seen you ask a question that is even close to stupid, just some occasional hints of naivety - which are to be completely expected during a learning process.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width