[fpc-pascal] constructor as procvar

David Emerson dle3ab at angelbase.com
Fri Mar 19 09:20:28 CET 2010


I'd like to pass a constructor as a procvar. Don't know if this is 
possible. Here is some silly illustrative code that doesn't work:

{$mode objfpc}

uses classes, sysutils;

type
  t_mammal = class
    public
      constructor create (color : byte); virtual;
    end;

  t_pig = class (t_mammal)
    // some fields, methods
    end;

  // the following fails:
  t_mammal_creator = t_mammal.constructor (color : byte) of object;

  // a list of animals...
  t_barnyard = class
    public
      function find_or_create_animal (color : byte;
          pass_create : t_mammal_creator) : t_mammal;
    end;

constructor t_mammal.create (color : byte);
  begin
  end;

function t_barnyard.find_or_create_animal (color : byte;
    pass_create : t_mammal_creator) : t_mammal;
  begin
    // look for the animal within the list. if not found:
    result := pass_create (color);
  end;

const
  brown = 18;

var
  pig_pen : t_barnyard;
  brown_pig : t_pig;
begin
  pig_pen := t_barnyard.create;
  brown_pig := t_pig (pig_pen.find_or_create_animal
      (brown, @t_pig.create));
end.


As you can (probably) see, I would like t_barnyard to be able to create 
any descendant of t_mammal. In the above example, I want it to create a 
brown pig if it doesn't find one, so I tried to pass the t_pig 
constructor, along with the brown parameter that said constructor will 
require. But I can't figure out the syntax. Perhaps this kind of thing 
is not supported?

Thanks!
~David.




More information about the fpc-pascal mailing list