Class composition

So, when setting up the composition of the class, the contained classes can be called using the default constructor, but not with the one that takes the parameters?

This confuses; let me give an example.

#include "Ah" class B { private: A legal; // this kind of composition is allowed A illegal(2,2); // this kind is not. }; 

Assuming both the default constructor and the one that takes 2 integers, there is only one of them. Why is this?

+4
source share
3 answers

This is valid, but you just need to write it differently. You need to use the list of initializers for the constructor of the composite class:

 #include "Ah" class B { private: A legal; // this kind of composition is allowed A illegal; // this kind is, too public: B(); }; B::B() : legal(), // optional, because this is the default illegal(2, 2) // now legal { } 
+8
source

You can provide constructor parameters, but you are not properly initializing your members.

 #include "Ah" class B { private: int x = 3; // you can't do this, either A a(2,2); }; 

Here is your solution, ctor-initializer :

 #include "Ah" class B { public: B() : x(3), a(2,2) {}; private: int x; A a; }; 
+2
source

a class declaration does NOT initialize the members that make up the class. hence, an error when you try to create an object inside a declaration.

member initialization takes place inside the class constructor. therefore you should write:

 #include "Ah" class B { public: B(); private: A a; }; B::B() : a(2,2) { } 
0
source

Source: https://habr.com/ru/post/1342440/


All Articles