[fpc-pascal] Problem with objects

Howard Page-Clark hdpc at talktalk.net
Wed Dec 23 13:57:37 CET 2015


On 23/12/2015 11:40, Santiago A. wrote:
> It's an object, not a class inherited from Tobject, so it hasn't create
> constructor.

Try this:
program simpleObjConsole;

type

   { TSimpleArrayString }

   TSimpleArrayString=object
   public
      List:array of String;
      constructor Init;
      destructor Destroy;
      function AddedTextIndex(const aText: string): integer;
      function StringCount: integer;
   end;

   constructor TSimpleArrayString.Init;
   begin
     SetLength(List, 0);
   end;

   destructor TSimpleArrayString.Destroy;
   begin
     SetLength(List, 0);
   end;

   function TSimpleArrayString.AddedTextIndex(const aText: string): integer;
   begin
     Result:=Length(List);
     SetLength(List, Result+1);
     List[Result]:=aText;
   end;

   function TSimpleArrayString.StringCount: integer;
   begin
     Result:=Length(List);
   end;

type
   { TDerivedArrayString }

   TDerivedArrayString=object(TSimpleArrayString)
      other_field:integer;
   public
      constructor Init(anInt: integer);
   end;

   constructor TDerivedArrayString.Init(anInt: integer);
   begin
     inherited Init;
     other_field:=anInt;
   end;

   procedure TestDerived;
   var
     idx, n: integer;
     das: TDerivedArrayString;
   begin
     das.Init(19);
     idx:=das.AddedTextIndex('test string');
     n:=das.StringCount;
     WriteLn('das has ',das.StringCount,' string(s), and 
das.other_field=',das.other_field);
     if (n > 0) then
       WriteLn('First string in das.List is "',das.List[idx],'" at 
index:',idx);
     ReadLn;
     das.Destroy;
   end;

begin
   TestDerived;
end.





---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus




More information about the fpc-pascal mailing list