Initializing Objects


The CThing object might be complete as soon as it’s created, but in real life most objects aren’t meaningful at the instant of creation. Visual Basic allows you to initialize a class or a form with the Initialize event and clean it up with the Terminate event, but that’s rarely enough information to construct a working object; most objects need more information from the user before their state is complete. This isn’t a problem with controls and forms because their initial state can be set with properties at design time. But classes can be initialized only
in code.


What you need (and what most object-oriented languages have) is a means to specify initialization data as part of the New syntax. If Visual Basic had constructors like other object-oriented languages, the syntax might look like this:

Set thing = New CThing(1, “Object”) ‘ You can’t do that

Instead, if you want to pass initialization data to a class, you must do so by convention and hope that your users will follow the rules. A traditional name I use for initialization methods is Create:

thing.Create 1, “Object”            ‘ Initialize with Create method

Another convention I use with objects that have one primary property is to make that one property the default:

Dim shsTitle As CSharedString
Set shsTitle = New CSharedString
shsTitle = “Share and share alike” ‘ Initialize with default property

In Visual Basic, most objects of substantial size and complexity will be invalid between the time you create them with New and the time you initialize them with a Create method (or whatever other technique you choose). You also have to worry about what to do if the user fails to follow your initialization convention—assert, raise an error, or let it be.


The lack of initialization—both of variables and of objects—is, in my opinion, the greatest flaw of the Visual Basic language. No other major high-level ­language shares this flaw. You’ll hear a lot more about initialization problems in this book. If I start to sound like a broken record, it’s because the language feels like a broken record.