Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Do Some Delphi Components Require "AOwner: TComponent" To Construct Them?

Tags:

delphi

vcl

It seems completely irrelevant to require a TComponent as an owner to instantiate an object of some kind. Why are there so many Delphi components that require this?

For example, TXMLDocument requires a TComponent object to instantiate.

Why is this and if there's a good reason, what should I be using in there to "do the right thing"?

like image 483
Dave Avatar asked Jan 23 '09 20:01

Dave


3 Answers

The owner component is supposed to manage all its owned components. The owned components gets destroyed automatically when the owner is destroyed.

This helps the developer who just drags components from the tool-palette, drops them on the form and just hooks up the events to get his work done without worrying about managing the lifetime of the components.

The form is the owner of all components dropped on it. The Application object is owner of the form. When the app is closed the Application object is destroyed which in turn destroys the forms and all the components.

But the owner is not really necessary when a components is created. If you pass Nil to the parameter, the component will be created without an owner and in this case it will be your responsibility to manage the component's lifetime.

like image 82
user9977 Avatar answered Sep 18 '22 03:09

user9977


All TComponent descendents require Owner, it is defined in TComponent constructor. The Owner component is responsible to destroy all the Owned components.

if you want to control the life time, you can pass nil as parameter.

like image 35
Cesar Romero Avatar answered Sep 20 '22 03:09

Cesar Romero


Just to add some extra information.

Each control also has a parent. (A TWinControl). Where the owner takes care of the lifetime, the parent takes care of showing the object.

For example a form has a panel and the panel has a button. In that case, the form owns the panel and the button. But the form is the parent of the panel and the panel is the parent of the button.

like image 41
Toon Krijthe Avatar answered Sep 20 '22 03:09

Toon Krijthe