7
votes

I have been completely unable to get forward class declarations in Delphi 2010. I have read the docs, read up on the web, and maybe I'm an idiot but I just cannot get anything to compile. Any help would be massively appreciated!

I have knocked up these two mickey mouse classes. Sure I know they need constructors etc to actually work, its just a demo for the problem I am having.

I have class MyParent which contains a TList of my other class MyChild. That's fine. But then inside MyChild I want to be able to set a reference to its parent object, not the TList but my MyParent class.

unit ForwardClassDeclarationTest;

interface

uses generics.collections;        

type
  MyChild = Class
  private
    ParentObect:MyParent;   <--I need to be able to make this accessable
  public
End;

type
  MyParent = Class
  public
    tlChildren:TList<MyChild>;
End;

implementation

end.

I need to create a forward declaration before both these class but am completely unable to get anything going. Thanks in advance to anyone inclined to help me out.

2

2 Answers

13
votes

@csharpdefector try this code

uses
  Generics.Collections;

type
   MyParent = Class;   // This is a forward class definition

  MyChild = Class
  private
    ParentObect:MyParent;
  public
  End;

  MyParent = Class // The MyParent class is now defined
  public
    tlChildren:TList<MyChild>;
  end;

implementation

end.

for more info you can see this link in delphibasics

13
votes

Before you declare MyChild, put : MyParent = class; and then declare MyChild. Then declare MyParent properly. And don't reuse the type keyword. It denotes a type-declaration block, not an individual type declaration, and class forward declaration only works inside the same block.