[fpc-pascal] Understanding virtual methods

Martin lazarus at mfriebe.de
Tue Aug 20 08:13:23 CEST 2013


On 20/08/2013 02:44, Xiangrong Fang wrote:
> Hi All,
>
> I am reading this document: 
> http://www.freepascal.org/docs-html/ref/refsu29.html and doing an 
> experiment with the following code:
>
> program project1;
> {$mode objfpc}{$H+}
> type
>   TBase = class
>     constructor Create; virtual;
>   end;
>   TDerived = class(TBase)
>     constructor Create; override;
>   end;
>
>
....
> The problem is, it makes NO DIFFERENCE at all in the following cases:
>
> CASE 1:
>
> TBase.Create;
> TDerived.Create;
>
> CASE 2:
>
> TBase.Create; virtual;
> TDerived.Create; virtual;
>
> CASE 3:
>
> TBase.Create; virtual;
> TDerived.Create; override;
>
> According to the document, "inherited" cannot be used in non-virtual 
> methods, and it is wrong to use virtual in sub-class. But my test 
> shows the contrary.   BTW, I am running Linux on 64bit platform.
>
>

Using virtual with constructor makes a difference, if you use "class of" 
types

type
   TBaseClass = class of TBase;
   TDerivedClass = class of TDerived;

Var
   bc: TBaseClass;

begin
   bc:= TBase;
   bc.create;

   bc:= TDerived;
   bc.create;  // will call Tderived.create, but only in case 3
end;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20130820/6c47df9b/attachment.html>


More information about the fpc-pascal mailing list