[fpc-pascal] Understanding virtual methods
Xiangrong Fang
xrfang at gmail.com
Tue Aug 20 03:44:59 CEST 2013
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;
var
c1, c2: TBase;
c3: TDerived;
constructor TDerived.Create;
begin
WriteLn('Entering TDerived.Create');
inherited Create;
WriteLn('Leaving TDerived.Create');
end;
constructor TBase.Create;
begin
WriteLn('Entering TBase.Create');
Writeln('Leaving TBase.Create');
end;
begin
WriteLn('Creating a TBase and assigning to TBase variable...');
c1 := TBase.Create;
WriteLn('Creating a TDerived and assigning to TBase variable...');
c2 := TDerived.Create;
WriteLn('Creating a TDerived and assigning to TDerived variable...');
c3 := TDerived.Create;
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.
Regards,
Shannon
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20130820/6cfb6482/attachment.html>
More information about the fpc-pascal
mailing list