[fpc-pascal] Problem with virtual constructors

cobines cobines at gmail.com
Wed Jun 1 19:17:01 CEST 2011


2011/6/1 Jorge Aldo G. de F. Junior <jagfj80 at gmail.com>:
> I am having problems with virtual methods.
>
> I have two classes, the second one is a descendent of the first :
>
> 1st:
>
>        TTreeNode = Class(TObject)
>        Public
>                Constructor Create(Const aOwner : TTreeNode); Virtual;
>
> 2nd :
>        TTreeNodeWithProperties = Class(TTreeNodeWithName)
>        Public
>                Constructor Create(Const aOwner : TTreeNodeWithProperties); Override;
>

TTreeNode is a different type than TTreeNodeWithProperties.

I think you should override the constructor with base type as param:

   Constructor Create(Const aOwner :  TTreeNode); Override;

At runtime check with:

if not (aOwner is TTreeNodeWithProperties) then
  raise exception....
inherited Create(aOwner);
...

If you define a different constructor with the derived type as param :

   Constructor Create(Const aOwner :  TTreeNodeWithProperties); Overload;

then if you're passing TTreeNode objects to   TTreeNodeWithProperties
constructor it will only call the base constructor.

--
cobines



More information about the fpc-pascal mailing list