The problem is that what you call “initialization” does not actually exist. Any members that are initialized, implicitly or explicitly, are initialized before the program enters your constructor.
In your code snippets, only the destination is displayed; it doesn't matter that you do this in the constructor body for the encapsulating object. This is still just an appointment.
Bar is a class, so your _bar member will be implicitly initialized, but in fact it cannot be, because the class does not have a constructor without arguments. To provide arguments, you must explicitly initialize this element yourself.
In C ++, we initialize the following elements:
class Foo { public: Foo(int valueBarNeeds) : _bar(valueBarNeeds) {} private: Bar _bar; };
You are also right to misunderstand new ; unlike Java, it should be used sparingly, since objects are fundamentally created by a simple declaration (and, if necessary, their definition). The use of new reserved for dynamic allocation in free storage and returns a pointer to use; this use should be rare. You have successfully fixed this in your final code snippet.
How to create a unified type available for other methods of the class, which is created by the constructor of parent objects?
If a member has a class type, it will always be initialized. You cannot have an object that does not exist. The closest you can get is encapsulating a pointer, not an object:
class Foo { public: Foo(int valueBarNeeds) : _bar(nullptr) { // some time later... _bar = new Bar(valueBarNeeds); } private: Bar* _bar; };
But this opens up a can of worms with regard to memory management and much more, and as explained above, you should avoid this if you really don't need it. Alternatives include smart pointers, but if possible, you should still adhere to the standard encapsulation of swamp objects. It should be rare that you need to consciously leave the object in an invalid state for a while.