[fpc-pascal] constructor as procvar

Florian Klaempfl florian at freepascal.org
Fri Mar 19 09:38:56 CET 2010


> 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?

Constructor procvars are indeed not supported but the way to achieve
what you want is to use class type variables (untested, but it should
illustrate the idea):

{$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_class = class of t_mammal;

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

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

function t_barnyard.find_or_create_animal (color : byte;
    mammal_creator: t_mammal_creator) : t_mammal;
  begin
    // look for the animal within the list. if not found:
    result := mammal_creator.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));
end.




More information about the fpc-pascal mailing list