Reputation: 799
I use Delphi XE3. I have two form, TParentForm and TChildForm. TParentForm contains Button1, and TChildForm is inherited from it.
Then when I operate Button1 in TParentForm, in the following procedure TParentFrm.Button2Click(Sender: TObject), is it operating on the instance of Button1 in ChildForm when I invoke ChildForm.Show and click Button1?
type
TParentFrm = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TChildForm = class(TParentFrm)
private
{ Private declarations }
public
{ Public declarations }
end;
var
ParentFrm: TParentFrm;
implementation
{$R *.dfm}
procedure TParentFrm.Button2Click(Sender: TObject);
begin
Button1.Caption := '&Test'; // Is it operating on Childform's button1 when I
// create and show child form and then click
//"Button2".
end;
Test unit:
procedure TForm1.Button1Click(Sender: TObject);
begin
ChildForm.Show;
end;
Upvotes: 1
Views: 338
Reputation: 12292
TChildForm
inherit from TParentForm
. Any member of TParentForm
- not strictly private - are inherited and accessible from TChildForm
instance. When you create an instance of TChildForm
, it has Button1 instance inherited from his parent class, that is TParentForm
.
Do not confuse a type (the definition of a class) and an instance (for short: the data allocated at runtime).
If you create two instances of TChildForm
(calling the constructor), you have two distinct instances of button1 and button2 as well. Button2 OnClick
handler of one instance will act of button1 instance in the same TChildForm
instance as itself.
In my opinion, you should stay away from form inheritance before fully understanding the general mechanism behind inheritance.
Upvotes: 1
Reputation: 8331
Short answer: Your code will change caption of the Button1 control that is on same form instance that the Button2 that you clicked on.
Long answer:
When you use code Button1.Caption := '&Test';
you basically instructs compute to go and find component named Button1
and change its Caption
property to &Test
. When computer performs this search it always does this within the instance of the form from which the code was called for.
So if your code is called from OnClick event that was fired by button that is placed on your ParentForm
it will affect the Button1
that is on your ParentForm
.
If the code is called from OnClick event that was fired from a button on your ChildForm
it will affect the Bu8tton1
that is on your child form.
Yes at this point your application have two buttons named Button1
. One is on your ParentForm
and another is on your ChildForm
In fact you can also create another instance of your ParentForm
and clicking on Button2
on that form will affect the Button1
on that instance of the form and not the original instance of your ParentForm
.
I hope my explanation is understandable enough. If not do let me know.
Upvotes: 4