Are mutually recursive classes possible?

I read how this can be done to work with forward ads.

class A { public: B *objB; void foo(){} } class B { public: A *objA; void foo(){} } 

Just wanted to confirm how feasible this project is?

 class A { public: B objB; void foo(){} } class B { public: A objA; void foo(){} } 

PS: If someone can also explain why / why it is impossible logically from the point of view of classes, and not just from the point of view of language, for example, quoting some example. What exactly does this mean in terms of classes?

+4
source share
4 answers

The second example is impossible. It says that the space allocated for A contains a place for B , which in turn contains a place for A , etc. This will require an infinite amount of memory and will require an infinite amount of time to build.

+9
source

No, this is impossible neither in terms of language, nor in terms of classes.

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

+2
source

Mutually recursive classes, such as your second example, are not possible. If each instance had a corresponding instance of another class, and since there is no basic case of stopping recursion, the size of the class will be infinite. Obviously, it would be difficult to create such a large class.

0
source

3.9 / 5 reports:

A class that has been declared but not defined, or an array of an unknown size or an incomplete type of an element, is an incompletely defined type of object. 43 Non-filled object types and void types are incomplete types (3.9.1). Objects should not be identified as incomplete.

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

-1
source

Source: https://habr.com/ru/post/1390653/


All Articles