tags:

views:

415

answers:

2

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.

+8  A: 

@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

RRUZ
Yeah, Thanks man! I was failing to put both classes under the same type statement ty very much.
csharpdefector
@Jim: They _do_ need to be under the same _type_ keyword, or else you run into the "not completely defined" compiler error. See Masons answer.
Paul-Jan
@Paul Yes, you are correct. I'll retract my comment.
Jim McKeeth
+7  A: 

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.

Mason Wheeler
Thanks mason, I got it. I was failing to put both my classes in the same type block as you mention.
csharpdefector