5

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 ?

Community
  • 1
  • 1
Amit Tomar
  • 4,800
  • 6
  • 50
  • 83

4 Answers4

11

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.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
3

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

Mutually recursive classes such as your second example are impossible. If each instance had a corresponding instance of the other class, and since there's no base case to stop th recursion, the size of the class would be infinite. Obviously it would be hard to instantiate such a large class.

Mark B
  • 95,107
  • 10
  • 109
  • 188
-1

3.9/5 tells :

A class that has been declared but not defined, or an array of unknown size or of incomplete element type, is an incompletely-defined object type.43 Incompletely-defined object types and the void types are incomplete types (3.9.1). Objects shall not be defined to have an incomplete type.

In your second example, class A tries to define a member variable with incomplete type, hence it is an ill formed.

BЈовић
  • 62,405
  • 41
  • 173
  • 273