Scopes and names can really be deceiving. A classes in a hierarchy can have members with identical names…
Posted by jpluimers on 2019/11/21
Examples like the one below from [WayBack] Scopes and names can really be deceiving. A root class and a descendant class can both have public fields, properties and methods with the same name… – Lars Fosdal – Google+ used to be part of the “language day” during my 5 day Delphi introductory courses.
Maybe I should find back more of those from the days, brush them up a little, then post them in a repository.
The thread has some nice references to tools that give better warnings and comparisons with other languages.
Anyone wanting to assist with that?
Example code
program PublicScope; {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils; type TClass1 = class public Test: Integer; constructor Create; virtual; procedure Dump; virtual; procedure Oops; property PropTest:Integer read Test; end; TClass2 = class(TClass1) public Test:Integer; constructor Create; override; procedure Dump; override; procedure Oops; property PropTest:Integer read Test; end; { TClass1 } constructor TClass1.Create; begin Test := 1; end; procedure TClass1.Dump; begin Writeln('TClass1:', Test); Writeln('TClass1.PropTest:', Test); end; procedure TClass1.Oops; begin Writeln('TClass1.Oops'); end; { TClass2 } constructor TClass2.Create; begin Inherited; Test := 2; end; procedure TClass2.Dump; begin Inherited; Writeln('TClass2.Test:', Test); Writeln('TClass2.PropTest:', Test); end; procedure TClass2.Oops; begin Writeln('TClass2.Oops'); end; procedure Test; var c: TClass1; begin c := TClass2.Create; try Writeln('c: ', c.Test); c.Dump; c.Oops; finally c.Free; end; end; begin try try Test; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; finally Write('Press any key: '); Readln; end; end.
Example output
c: 1 TClass1:1 TClass1.PropTest:1 TClass2.Test:2 TClass2.PropTest:2 TClass1.Oops Press any key:
–jeroen
Leave a Reply