How to make it possible to create an instance of class B
only after an instance of class A
been created?
- 2You'd better describe your task. What you are asking is like trying to solve a problem incorrectly - ixSci
- If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky ♦
|
2 answers
Constructor B
must accept A
or some object that can only be obtained from A
:
struct B { B(const A&); };
- Otherwise nothing ?? - ilyaoleynikov
- @ilyaoleynikov in a normal way - no. - Abyx
|
Your task can be interpreted in two ways. If like “if no A
created in the program, then creation B
should generate an exception” - then this is one ... Here I would suggest in class A
monitor the presence with, for example, a class variable (not an instance) and check it in constructor class B
If it is necessary that, before creating B
, it is necessary to create — anywhere, whatever — an object A
, then you can use the static variable A
in the constructor B
An even simpler option is to add object A
to class B
as a member — then it will definitely be created before creating B
|