delphi - I have two units and a class in each unit that need each other to function. How do I avoid a circular reference? -
i have 2 classes, classa
, classb
, each in own seperate unit, unita
, unitb
.
unita
uses unitb
. allows classa
call constructor classb
. part of classb's
functionality requires use of classa's
methods. cannot make unitb
use unita
, else causes circular reference. alternative have in allowing classb
access classa's
methods within unitb
?
it depends lot on how 2 classes need use each other. if 1 class uses other in implementation, not interface, can move unit in uses clause interface
section down implementation
section instead.
this work either way around:
unita; interface uses classes, unitb; type tclassa = class(tobject) end; ...
.
unitb; interface uses classes; type tclassb = class(tobject) end; implementation uses unita; ...
however, if interface of both classes rely on each other, have no choice put both classes in same unit (and using forward declarations).
unita; interface uses classes; type tclassa = class; tclassb = class; tclassa = class(tobject) end; tclassb = class(tobject) end; ...
in rare cases, might able move entire class definition down implementation
. wouldn't useful though if needed use class elsewhere.
unitb; interface implementation uses classes, unita; type tclassb = class(tobject) end; ...
depending on complexity, it's common practice put commonly shared code in separate unit of own. example constants, record array types, global variables, etc. common unit shall not use other of these units.