Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare two inter-linked classes?

I have a question similar to this, but in delphi.

type
  TThreadPopulator = class(TThread)
  private
    _owner:TASyncPopulator; //Undeclared identifier
  end;

type
  TAsyncPopulator = class
  private
    _updater: TThreadPopulator;
  end;

Solution of mentioned question is not applicable to delphi

like image 593
Niyoko Avatar asked Oct 22 '12 05:10

Niyoko


3 Answers

See Forward Declarations and Mutually Dependent Classes documentation.

type (* start type section - one unified section "to rule them all" *)

  TAsyncPopulator = class; (* forward declaration, it basically serves just to
  fix SizeOf(TAsyncPopulator) so compiler would be able to draft dependent types'
  in-memory layout. Down the CPU level `class` and `pointer` is the same, so now 
  Delphi knows SizeOf(TAsyncPopulator) = SizeOf(pointer) to compose further types *)

  TThreadPopulator = class(TThread)
  private
    _owner:TASyncPopulator;
  end;
    
  TAsyncPopulator = class (* the final declaration now, it should go WITHIN 
  that very TYPE-section where the forward declaration was made! *)
  private
    _updater: TThreadPopulator;
  end;

  ....

type 
(* now, that you had BOTH forward and final declarations for TAsyncPopulator 
   spelled out above, you finally may start another TYPE-section, if you choose so. 
   But only after them both, and never should a new `type` section be inserted 
   in between those declarations. *)
  ....

Use the source, Luke! Your Delphi installation has full VCL and RTL sources for you to read and watch and learn. And it uses this template a lot. Every time when you ask yourself "how I could do it", just think along "how did Borland do it" and pretty chance that you can already get a ready-made example in Delphi-provided sources.

like image 69
Arioch 'The Avatar answered Nov 11 '22 22:11

Arioch 'The


Use this before any class definition. Forward class works in Delphi 2010. I don't know witch version of delphi you have but it's the only solution I can think off.

type   
 TAsyncPopulator = Class;

Hope I helped

like image 33
opc0de Avatar answered Nov 11 '22 21:11

opc0de


Besides using a forward declaration, you can also create a subclass to solve this:

TThreadPopulator = class(TThread)
  type 
    TAsyncPopulator = class 
      _updater: TThreadPopulator;  
    end;

  var 
    owner: TAsyncPopulator;
end;
like image 2
Wouter van Nifterick Avatar answered Nov 11 '22 22:11

Wouter van Nifterick