Search code examples
delphidelphi-10.2-tokyo

Delphi virtual constructor


I was reading this article because I wanted to understand the usefulness of class of [ClassName] and I have seen that they declare a virtual constructor. So I have made a test that you can see here:

enter image description here

I understand (from that article) that virtual constructors are useful when I don't know at compile-time the class I want to construct and I can use the class of. In the code I have shown above, what is the difference?

If I declared TFirst constructor as virtual without overriding TSecond I'll get the warning of course ad I can remove that with a reintroduce or override. But isn't the constructor automatically overridden (look at the code on the left)? I think that they are equivalet.


Solution

  • Execute this code with both variants and you will see the difference.

    type
      TFirstClass = class of TFirst;
    
    constructor TFirst.Create;
    begin
      Writeln('TFirst.Create');
    end;
    
    constructor TSecond.Create;
    begin
      Writeln('TSecond.Create');
    end;
    
    var
      firstClass: TFirstClass;
      first: TFirst;
    begin
      firstClass := TSecond;
      first := firstClass.Create;
    end.