Wednesday, October 31, 2007

DN4DP#29: .NET vs Win32: Constructors

This post continues the series of The Delphi Language Chapter teasers from Jon Shemitz’ .NET 2.0 for Delphi Programmers book.

Last time we looked at class references. This posts covers .NET vs Win32 constructors.

Note that I do not get any royalties from the book and I highly recommend that you get your own copy – for instance at Amazon.

"Constructors

While it is a good rule in Win32 to have all constructors call an inherited or peer constructor, the compiler does not enforce it. In .NET the runtime refuses to load types that break this rule. In addition you cannot access inherited fields or call any methods until you have called an inherited constructor.

type
TBar = class
protected
FInheritedField: integer;
end;
TFoo = class(TBar)
private
FField: integer;
procedure Method;
public
constructor Create;
end;

constructor TFoo.Create;
begin
FField := 42;
{$IFNDEF CLR}
Method;
FInheritedField := 13;
{$ENDIF}
inherited Create;
FInheritedField := 13;
Method;
end;

Note that unlike C#, in Delphi you can still modify the fields of the current instance before calling the inherited constructor."

No comments:



Copyright © 2004-2007 by Hallvard Vassbotn