[fpc-pascal] Understanding virtual methods
Xiangrong Fang
xrfang at gmail.com
Tue Aug 20 08:32:54 CEST 2013
Thanks. Do you mean that the rules I see in the document apply to NORMAL
virtual methods, but not virtual constructors?
Also, I have a related question: it seems that to override methods in
ancestor it is required that the method has same signature, however
reintroduce will not have such limitations. Example:
constructor TBase.Create; virtual;
... ...
constructor TDerived.Create(AParam: TParamType); override
The above code won't compile until I change the override keyword to
"reintroduce". Because the compiler complains that there is no Create()
with the same signature in the base class.
However, if I use reintroduce, according to the document, the compiler will
make the Create method STATIC and hide the create method in the base class,
in another word, it is then invalid to call TDerived.Create; (without
param). What is the mechanism here?? Also, if I do not use override or
reintroduce, instead, put an "overload" there, it will make BOTH version of
the constructor visible, AND the "inherited" keyword also works well!
Could anyone explain these messes about: virtual, override, overload,
reintroduce??
Thanks a lot.
Shannon
2013/8/20 Martin <lazarus at mfriebe.de>
> 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;
>
> _______________________________________________
> fpc-pascal maillist - fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20130820/dd107012/attachment.html>
More information about the fpc-pascal
mailing list