Ownership
Components have the capability of owning other components. A component's owner is specified by its Owner property. When a component owns other components, it's responsible for freeing the components it owns when it's destroyed. Typically, the form owns all components that appear on it. When you place a component on a form in the form designer, the form automatically becomes the component's owner. When you create a component at runtime, you must pass the ownership of the component to the component's Create constructor; it's assigned to the new component's Owner property. The following line shows how to pass the form's implicit Self variable to a TButton.Create() constructor, thus making the form the owner of the newly created component:
MyButton := TButton.Create(self);
When the form is destroyed, the TButton instance to which MyButton refers is also destroyed. This is handled internally in the VCL. Essentially, the form iterates through the components referred to by its Components array property (explained in more detail shortly) and destroys them.
It's possible to create a component without an owner by passing nil to the component's Create() method. However, when this is done, it's your responsibility to destroy the component programmatically. The following code shows this technique:
MyTable := TTable.Create(nil) try { Do stuff with MyTable } finally MyTable.Free; end;
When using this technique, you should use a try..finally block to ensure that you free up any allocated resources if an exception is raised. You wouldn't use this technique except in specific circumstances when it's impossible to pass an owner to the component.
Another property associated with ownership is the Components property. The Components property is an array property that maintains a list of all components belonging to a component. For example, to loop through all the components on a form to show their classnames, execute the following code:
var i: integer; begin for i := 0 to ComponentCount - 1 do ShowMessage(Components[i].ClassName); end;
Obviously, you'll probably perform a more meaningful operation on these components. The preceding code merely illustrates the technique.