Maybe I'm a purist when it comes to the language, but I've encountered this feature, which is cool and annoying at the same time. Consider this code:
Program Project1;
Program Project1;
Type
{ Class1 }
Class1 = class
private
fName : String;
public
function Clone: Class1; virtual;
property Name : String read fName write fName;
End;
{ Class2 }
Class2 = class(Class1)
public
function Clone: Class2; override;
End;
{ Class1 }
Function Class1.Clone: Class1;
Begin
Result := Class1.Create;
Result.Name := fName;
End;
{ Class2 }
Function Class2.Clone: Class2;
Begin
Result := Class2.Create;
Result.Name := fName;
End;
Var C1 : Class1;
C2a, C2b : Class2;
Begin
C2a := Class2.Create;
C2a.Name := 'Class 2';
C1 := C2a;
//Next code line -- compilation error:
//Incompatible types: got "Class1" expected "Class2"
C2b := C1.Clone;
End.
Nothing fancy here, but look at the signature of the overridden method
Clone. The initial method returns
Class1, the overridden method returns
Class2. Shouldn't the compiler flag it as an error? In fact it complains (rightly so) when I assign the return of this function from an instance of
Class1 to an instance of
Class2, as indicated by the comment in the code.
Thoughts?