Sunday, 24 November 2013

Circular references and forward declarations

In OOP, circular references occur when a class A needs to refer to another class B which also needs to refer to the referring class A.

As classes need to be declared before they are used, the declaration of class B will have to precede the declaration of class A, but the declaration of class A has to precede that of class B as well - a clearly impossible situation. Furthermore, it is troublesome to have to specify the order of linking files, especially when there is a large number of source files.

The solution to this is to use forward declarations. Taking C++ as an example,


A.h

#pragma once
#include <B.h>


class B;

class A
{
B b;
}



B.h

#pragma once
#include <B.h>
 

class A;

class B
{
A a;
}


The lines class B and class A are called forward declarations. They let the compiler know that this class exists without us having to define it first. Therefore, this circumvents the problem of circular references.

Of course, until the compiler has "seen" the definitions, members of the class are not known and cannot be accessed.

No comments:

Post a Comment