Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are mutually recursive classes possible?

I read how this can be made to work using forward declarations.

class A
{
    public:
    B *objB;

    void foo(){}
}

class B
{
    public:
    A *objA;

    void foo(){}
}

Just wanted to confirm if this design is ever possible ?

class A
{
    public:
    B objB;

    void foo(){}
}

class B
{
    public:
    A objA;

    void foo(){}
}

PS: If someone could also please explain why/why not this is possible logically in terms of classes, rather than just in terms of language, like by quoting some example. What exactly this signify in terms of classes ?

like image 538
Amit Tomar Avatar asked Jan 12 '12 14:01

Amit Tomar


2 Answers

The second example is not possible. It says that the space allocated for an A contains room for a B, which in turn contains room for an A, etc. This would require an infinite amount of memory, and would take an infinite amount of time to construct.

like image 151
Oliver Charlesworth Avatar answered Sep 28 '22 12:09

Oliver Charlesworth


No, it is not possible either in terms of language or in terms of classes.

In terms of classes: Every A instance contains a B instance which contains an A instance which... => infinite recursion. This is not a problem with the pointer version because the pointer may not point to a valid object, or all A pointers may point to the same object, etc.

like image 33
Jon Avatar answered Sep 28 '22 13:09

Jon