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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With