What is the purpose of forward declaration?

C++ (like C) was designed to be implementable by a single-pass compiler. Forward references are necessary in cases where the compiler needs to know that a symbol refers to a class before the class is actually defined. The classic example of this is when two classes need to contain pointers to each other. i.e.

class B;

class A {
  B* b;
};

class B {
  A* a;
};

Without the forward reference to B, the compiler could not successfully parse the definition for A and you can’t fix the problem by putting the definition of B before A.

In a language like C#, which needs a two-pass compiler, you don’t need forward references

class A {
  B b;
}

class B {
  A a;
}

because the compiler’s first pass simply picks up all symbol definitions. When the compiler makes its second pass, it can say “I know B is a class because I saw the definition on my first pass”.

Leave a Comment