Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Class and contained classes 1

Status
Not open for further replies.

fluke030

Programmer
Nov 25, 2005
8
US
Hello,

I have a class (Tworld) that contains an array of TAgents (both defined by me). I need the instances of TAgent to be able to look up at an instance of World. My attempts so far have resulted in compilation errors. What is the best way to accomplish this task?

Thank you,
Frank
 
A little more information.

Code:
TAgent = class(TPersistent)
   Parent: TWorld;
...
end;

And passing the self through the constructor results in an "Undeclared identifier" message because TWorld is in another file. However, if I add cWorld to the uses clause, it returns a "circular reference" error because cWorld uses cAgent.

Frank
 

It sounds like you need to use a "forward declaration" of Tworld so that you can reference that object while defining your TAgent object which needs to be defined before the full definition of the Tworld object.

See thread102-1147645 for an example.

 
You cannot have two class declarations in the interface section of separate units that reference each other. ie

Code:
unit WorldUnit;

interface

uses
  AgentUnit;

type
  TWorld = class(TObject)
    FAgents: array of TAgent;
  end;

implementation

end.
Code:
unit AgentUnit;

interface

uses
  WorldUnit;

type
  TAgent = class(TObject)
    FParent: TWorld;
  end;

implementation

end.

because neither unit can be compiled without the other being compiled - hence circular reference.

One way to get around this is to change one of the references to an ancestor class of the object required. eg.

Code:
unit AgentUnit;

interface

type
  TAgent = class(TObject)
    FParent: TObject;  // TObject is an ancestor of TWorld
  public
    constructor Create(AParent: TObject);
  end;

implementation

uses
  WorldUnit;  // can be moved here, coz not referenced above

constructor TAgent.Create(AParent: TObject);
begin
  if AParent is TWorld then
  begin
    inherited Create;
    FParent := AParent;
  end
  else
    raise Exception.Create('Parent must be TWorld');
end;

end.

With this type checking in place, you're guaranteed that FParent will contain an object of type TWorld, otherwise the TAgent object never gets instantiated (because no call to the inherited Create takes place)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top