[fpc-pascal] How to make class constructor body calls descendant's overriden method/property?

Joao Morais jcmoraisjr at gmail.com
Sat Nov 17 22:40:13 CET 2012


On Sat, Nov 17, 2012 at 12:48 PM, leledumbo <leledumbo_cool at yahoo.co.id> wrote:
> Cross posted from stackoverflow:
> http://stackoverflow.com/questions/13431079/how-to-make-class-constructor-body-calls-descendants-overriden-method-property
>
> I'm writing an ORM framework and got stuck in a way to automatically
> determine table name from class name. In my base object for the ORM to work,
> I have:
>
> TghModel = class
> ...
>   class var FTableName: String;
>   class constructor Create;
> ...
>
> whose implementation is:
>
> class constructor TghModel.Create;
> begin
>   FTableName := ClassName;
>   Delete(FTableName,1,1); // Delete 'T'
> end;
>
> My assumption was that ClassName method will return the real class name.
> e.g. if I have:
>
> TUsers = class(TghModel)
>
> then FTableName will be initialized to TUsers instead of TghModel, which is
> wrong. I want to avoid users to make class constructor for each classes
> inheriting from TghModel, especially because the content would be totally
> the same as in TghModel.Create. Is there any way to implement it?

Tell the user of the framework to do something like this for every
class of your model:

  initialization
    TUser.RegisterClass;
    TProduct.RegisterClass;
    ...

or

  initialization
    RegisterClasses([TUser, TProduct, ...]);

Btw I've tried the following code:

  program Project1;

  {$mode objfpc}{$H+}

  type
    TBase = class(TObject)
    public
      class var name: string;
    end;

    TConcrete = class(TBase);

  begin
    TBase.name := 'base';
    TConcrete.name := 'concrete';
    writeln('TBase.name: ', TBase.name);
  end.

whose output is:

  TBase.name: concrete

which means, if I'm not mistaken, the class var "name" is shared
between all decendants, so perhaps your approach won't work very well.
Please correct me if I'm wrong.

Joao Morais



More information about the fpc-pascal mailing list