- The Class Hierarchy
- Creating a New Class
- Declaration and Instantiation
- Constructors and Destructors
- Garbage Collection
- Object Operators
- Adding and Overriding Methods
- Calling the Overridden Method
- Access Scope: Public, Private, Protected
- Setting Properties with Methods
- Default and Optional Parameters
- Declaring Variables Static and Const
- Revisiting the StringParser Module
- Example: Creating a Properties Class
- Data-Oriented Classes and Visual Basic Data Types
- Advanced Techniques
One thing you may have noticed is that I haven't had to say anything about how to manage the computer's memory in REALbasic. In programming languages such as C, much of the work you do centers on allocating memory for data and making sure that memory is freed up when you are done with it. In REALbasic, you don't have to worry about this very much because REALbasic uses a process called garbage collection, which means that it automatically purges objects from memory when appropriate. The operative phrase here is "when appropriate."
Garbage collection uses a process called reference counting to keep track of objects. Variables that refer to objects don't behave like scalar variables do. Although you may have two scalar variables whose value is "5", it does not mean that these two scalar values are references to the same location in memory. Objects, on the other hand, can easily have more than one variable serve as a reference to their location.
Reference counting refers to keeping track of how many variables (local variables and properties) reference a particular object. As long as at least one reference to an object exists, the object stays resident in memory. After the last reference goes away, the object is dumped. This is when the Destructor method is called.
In most cases you won't have to worry about memory, but there are some situations where references inadvertently do not go away. This can sometimes result in a situation where new objects are being instantiated while old objects are still hanging around in memory, which means that your program will consume larger and larger amounts of memory as the application runs. This is called a memory leak, and memory leaks are bad.
The trouble usually starts when you have two objects that each refer to each other. Because object A has a reference to object B and object B has a reference to object A, neither object is ever going to be garbage collected. The way around this is to implement a method for object A that explicitly sets the reference to object B to Nil. Do the same thing with object B. Now when object A is destroyed, the reference to object B is safely removed (or, more accurately, the reference count to object B is decremented).