Virtual functions in constructors, why do languages differ?

前端 未结 6 1442
攒了一身酷
攒了一身酷 2021-01-04 09:56

In C++ when a virtual function is called from within a constructor it doesn\'t behave like a virtual function.

I think everyone who encountered this behavior for the

6条回答
  •  鱼传尺愫
    2021-01-04 10:23

    Delphi makes good use of virtual constructors in the VCL GUI framework:

    type
      TComponent = class
      public
        constructor Create(AOwner: TComponent); virtual; // virtual constructor
      end;
    
      TMyEdit = class(TComponent)
      public
        constructor Create(AOwner: TComponent); override; // override virtual constructor
      end;
    
      TMyButton = class(TComponent)
      public
        constructor Create(AOwner: TComponent); override; // override virtual constructor
      end;
    
      TComponentClass = class of TComponent;
    
    function CreateAComponent(ComponentClass: TComponentClass; AOwner: TComponent): TComponent;
    begin
      Result := ComponentClass.Create(AOwner);
    end;
    
    var
      MyEdit: TMyEdit;
      MyButton: TMyButton;
    begin
      MyEdit := CreateAComponent(TMyEdit, Form) as TMyEdit;
      MyButton := CreateAComponent(TMyButton, Form) as TMyButton;
    end;
    

提交回复
热议问题