For example, consider the simple program shown in Figure *.
Even though this program only includes three declarations at the top level, it is enough
to show that several "obvious" strategies for processing the declarations won't work.
class Program {
Forward x;
class Forward {
int counter;
void relay() {
x.action();
}
void action() {
counter = counter + 1;
}
void init() {
counter = 0;
}
int get() {
return counter;
}
}
int main() {
x = new Forward;
x.relay();
return x.get();
}
}
Coping with forward references
- If you try processing the declarations in order, you get into trouble immediately.
When you go to process the declaration of the variable x, you discover that it is
supposed to be of type Forward, but you haven't processed the declaration
of Forward yet. You will want to put a pointer to the declaration descriptor
for Forward into the declaration descriptor for x, but the descriptor for
Forward won't even exist yet.
- If you try to process the declaration of Forward before x, however, you
will just run into a different problem. Forward references x in its relay method.
If there is no declaration descriptor or binding for x, how can you resolve this
reference to x?
- If you try the last possibility, processing the method main first, you again encounter
references to x before you have created its declaration descriptor.