We help IT Professionals succeed at work.

Undeclared Identifier Error

Richard2000
Richard2000 asked
on
Hi,

I have 2 classes both in the same unit.  Both classes have identifiers that reference each other.  As a result the code will not compile.  I need the components to reference each other because they are related.  How do I make it compile and function correctly?

Thanks!

Richard

Here is the code...

unit Unit2;

interface

uses
  classes;

type
  TComp1 = class(TComponent)
  private
  public
    Comp2: TComp2;
  end;

type
  TComp2 = class(TComponent)
  private
  public
    Comp1: TComp1;
  end;

implementation

end.
Comment
Watch Question

Software Engineer, Advisory
CERTIFIED EXPERT
Top Expert 2005
Commented:

Richard,

try this

type
  TComp2 = class;
  TComp1 = class(TComponent)
 private
 public
   Comp2: TComp2;
 end;

 TComp2 = class(TComponent)
 private
 public
   Comp1: TComp1;
 end;

Commented:
HI
I think that you must avoid this declaration
It is not object orinted at all .
please give a reason why you must do it , i think that you can declere  Tcomp3 and use it in Tcomp1,Tcomp2 .
Russell LibbySoftware Engineer, Advisory
CERTIFIED EXPERT
Top Expert 2005

Commented:

Richard,

What you are trying to do is perfectly valid, and demonstrates a forward class declaration. The issue is that TComp1 needs to have a clue what TComp2 is, and visa versa. So, you declare TComp2 as type class, define TComp1, then finish the definition for TComp2.

Check out Delphi's classes.pas, it's done numerous times there, as well as in many other Delphi standard units.

Russell

Author

Commented:
Hi,

Thanks for your comments.  I've tried the code and it works fine.

The reason I need to have 2 components that reference each other is because they are separate objects, but are related.  Comp1 maintains a list of Comp2's that are accessed through Comp1.  However, Comp2 still needs a reference to Comp1 so it is possible to know if it belongs to the list or not by accessing Comp2.

A good example of the above in the VCL is TPageControl and TTabSheet.  TPageControl provides access to all of the TTabSheet's it has in it's list.  TTabSheet also has a PageControl property so that it is easy to tell what PageControl it belongs to (and to add/remove tabsheets from the TPageControl).

I'm not sure of any other way of doing it.  In this case declaring another class wouldn't work.  I suppose that if Borland use this technique in the VCL, then it is okay for me to do the same.

Thanks!

Richard

Explore More ContentExplore courses, solutions, and other research materials related to this topic.