[fpc-pascal] why constructor of TObject is NOT virtual but destructor is?

Sven Barth pascaldragon at googlemail.com
Mon May 5 08:04:19 CEST 2014


Am 05.05.2014 04:13 schrieb "Xiangrong Fang" <xrfang at gmail.com>:
> My questions are:
>
> 1) if the above understanding is correct AND COMPLETE, why the
constructor of TObject is not virtual? What problem will appear IF we make
it virtual?

Virtual constructors are basically only needed if you want to create an
object using a class reference variable. So there's no need to burden every
constructor in the (Object Pascal) world with the overhead of a virtual
method call...

>
> 2) What is the purpose of making destructor of TObject virtual?

The destructor needs to virtual so that the correct one is called no matter
what static type a variable has. Imagine you have a TFoo which inherits
from TObject and you'd not have a virtual destructor, but only a
non-virtual one in both classes. Now if you call Free it would always be
TObject.Destroy that is called and not TFoo.Destroy, because Free is
declared in TObject and has no way if knowing that there is a TRio
descendant that has a constructor as well. And here virtual methods cone to
the rescue...

Regards,
Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20140505/c2139cdf/attachment.html>


More information about the fpc-pascal mailing list