CS1102C Miniature 8

How do we define two classes A and B, but A uses B and B uses A?

Say you want to define two classes A and B, such that A uses B and B uses A, as in the following:

class A {
private:
    B b;
// ...
};

class B {
private:
    A a;
// ...
};

And you get into a compilation error no matter you declare A before B or B before A.

The solution is simple:

// forward class declaration
class B;

class A {
private:
    B b;
// ...
};

class B {
private:
    A a;
// ...
};

Just add a forward class declaration for class B prior to defining class A to tell the compiler that you are going to define class B later. Of course, you have to make sure that you actually define class B.

Such forward declarations can also be used in C functions as well, particularly in recursive functions. For example:

// forward function declaration
int beta(int n);

int alpha(int n) {
    if (n <= 0)
        return 0;
    else
        return beta(n / 2) + 1;
}

int beta(int n) {
    if (n <= 0)
        return 0;
    else
        return alpha(n - 1) + 1;
}

Back to Index