Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access base (super) class in Delphi?

In C# i can access base class by base keyword, and in java i can access it by super keyword. How to do that in delphi? suppose I have following code:

  type
    TForm3 = class(TForm)
  private
    procedure _setCaption(Value:String);
  public
    property Caption:string write _setCaption; //adding override here gives error
  end;

  implementation


procedure TForm3._setCaption(Value: String);
begin
  Self.Caption := Value; //it gives stack overflow      
end;
like image 580
Niyoko Avatar asked Sep 20 '12 03:09

Niyoko


3 Answers

You are getting a stackoveflow exception because the line

Self.Caption := Value;

is recursive.

You can access the parent property Caption casting the Self property to the base class like so :

procedure TForm3._setCaption(const Value: string);
begin
   TForm(Self).Caption := Value;
end;

or using the inherited keyword

procedure TForm3._setCaption(const Value: string);
begin
   inherited Caption := Value;
end;
like image 121
RRUZ Avatar answered Nov 05 '22 00:11

RRUZ


base (C#) = super (java) = inherited (Object Pascal) (*)

The 3 keywords works in the same way.

1) Call base class constructor
2) Call base class methods
3) Assign values to base class properties (assume they are not private, only protected and public are allowed)
4) Call base class destructor (Object Pascal only. C# and Java doesn't have destructors)


(*) Object Pascal is preferable instead of Delphi or Free Pascal because Object Pascal is the name of a program language while Delphi and Free Pascal are compilers of Object Pascal.

like image 24
Zé do Boné Avatar answered Nov 04 '22 22:11

Zé do Boné


You should use inherited keyword:

procedure TForm3._setCaption(Value: String); 
begin 
  inherited Caption := Value;
end;
like image 11
da-soft Avatar answered Nov 04 '22 23:11

da-soft