Initializing Class Objects and Internal Variables


Class modules have a Class_Initialize event that you can use to initialize private variables. But because Class_Initialize is an event, you can’t use it to pass data to the class object from its creator. In other words, you can tell a class how to initialize its own variables, but you can’t initialize the class object. Yet many classes are completely undefined and unusable until they are initialized.


What you need is a way to combine declaration and initialization:

Dim pgStar As New CPictureGlass = (pbStar)

Instead, you must initialize by convention. Give your class a Create method, and tell users that they must always call it before using a class object:

Dim pgStar As New CPictureGlass
pgStar.Create pbStar

The bottom line is that callers who try to reference an object before initializing it with the Create method get random results. Convention isn’t a very good way to enforce good behavior—better to leave users no way but the right way.


Most object-oriented languages allow you to initialize objects in their declarations. Unfortunately, initialization syntax can get very complex, especially with objects consisting of other objects. Inheritance or delegation adds even more complications. It’s a difficult problem in language design, which might be why Visual Basic programmers put off dealing with it in version 5. Let’s hope they’ll bite the bullet and do what needs to be done, however difficult, next time.