-1

It is possible to make circular references from class A to class B and vica-versa using forward declarations

class class_a;
class class_b;

class class_a {
    class_a(class_b& arg) : ref_to_b(arg){}; // constructor
    class_b& ref_to_b;
};

class class_b {
    class_b(class_a& arg) : ref_to_a(arg){}; // constructor
    class_a& ref_to_a;
};

How to create instances of such classes?

  • Yes, it's possible, but the program will be ill-formed. Is it just out of curiosity or a real problem? – 273K Oct 12 '22 at 06:39
  • Assume you have a driver class and a handler class. Driver should call handler's callbacks, and handle should call driver's methods – Xeenych Xeenych Oct 12 '22 at 06:41
  • Use pointers and subscribe/unsubscribe ideoms. – 273K Oct 12 '22 at 06:43
  • Yeah, this is simple, but what about binding two classes in constructors? Constructors can be made constexpr and binding may happen at compile-time – Xeenych Xeenych Oct 12 '22 at 06:44
  • If the two classes _must_ reference instances of one another (and non-rebindable), why do they need to be separate classes at all? – user17732522 Oct 12 '22 at 07:20
  • I mean what you want is possible, but effectively the class objects would be seriously limited in their normal use as class objects. – user17732522 Oct 12 '22 at 07:23

1 Answers1

1

At global scope you can declare the classes before initializing them to obtain references:

extern class_a a;
extern class_b b;

class_a a{b};
class_b b{a};

And now that we have those we can use placement new to create more such pairs:

auto a2 = new class_a(a);
auto b2 = new class_b{a2};
a2 = new(a2) class_a{b2};

Now a2 and b2 point to another pair of such class objects.

However, I doubt that this is useful in practice.

user17732522
  • 53,019
  • 2
  • 56
  • 105