0

Let's say I have a class A which should hold an instance of class B (pointer or straight), and for some reasons B cannot be initiated in A's MIL, but later in the constructor's body.

For what I understand I have 2 options:

  1. Init B in MIL (with empty or partial constructor), and set up relevant fields later.
  2. Hold B* and dynamically allocate it when I have all the information. This will require new though.

I guess option 1 is better performance-wise. If performance is not an issue, which should I prefer?

Elad Weiss
  • 3,140
  • 3
  • 13
  • 37
  • 5
    If you have all the information you need later in the constructor body, you could write a helper functions and remove the constructor body, calling the functions in the member initializer list – Justin Dec 28 '17 at 07:26
  • 3
    C++17 also adds `std::optional` – StoryTeller - Unslander Monica Dec 28 '17 at 07:26
  • 1
    Option 2 could use a `std::unique_ptr`. Don't know if this works better or worse than the other suggestions offered due to the unknown circumstances of your case. Need more context to give a decent answer. – user4581301 Dec 28 '17 at 07:29
  • Possible duplicate of [Is the pImpl idiom really used in practice?](https://stackoverflow.com/questions/8972588/is-the-pimpl-idiom-really-used-in-practice) – user2672165 Dec 28 '17 at 07:57

1 Answers1

1

I would say this generally depends on whether the a is of any use if the b allocation/initialization fails. If it's useless without b make it part of the ctor and let the exception propagate if either the b allocation or initialization fails. If a can be used without b then the b initialization can be put off.

SoronelHaetir
  • 11,346
  • 1
  • 8
  • 18