Classes declared in the same unit are implicit "friends" (to use C++ terminology), so they have access to the private and protected members of other classes declared in that unit.
One of the shortcomings of Object Pascal is shown by your example. Type1 has a member of Type2, and Type2 has a member of Type1. For this to work in Object Pascal, you have to provide the full declaration and implementation of both Type1 and Type2 in the same unit. In C++, this is easily accomplished because you can forward declare a type in one header, but provide the actual declaration in another header. Thus you would have something like this:
Item.h
Code:
class TMap;
class TItem
{
private:
TMap *Map;
};
Map.h
Code:
class TItem;
class TMap
{
private:
TList *Items;
protected:
void AddItem(TItem *Item);
};
What you could do is to separate the classes into .inc files. With this, you would have something like the following:
GameObjects.pas
Code:
unit GameObjects;
interface
uses
Classes;
type
// Forward declarations
TMap = class;
{$I ItemInterface.inc}
{$I MapInterface.inc}
implementation
{$I MapImplementation.inc}
end.
ItemInterface.inc
Code:
TItem = class
protected
Map: TMap;
end;
MapInterface.inc
Code:
TMap = class
private
Items: TList;
protected
procedure AddItem(Item: TItem);
end;
MapImplementation.inc
Code:
procedure TMap.AddItem(Item: TItem);
begin
Items.Add(Item);
DrawItems.Add(Item);
Item.Map := Self;
end;
Advantages:
:arrow: Files are a lot smaller.
Disadvantages:
:arrow: Interface is in a separate file to the implementation (but then, that is what C++ is like anyway)
:arrow: No code completion or class completion in the Delphi IDE.
:arrow: A lot more files to manage.
Bookmarks