Definition: Composition describes a class that references one or more objects of other classes in instance variables.
classLine{ Point p1, p2;};
C++
Java
Members are objects
Members are pointers
Construction
Question: In what order are the constructors called?
#include <iostream>usingnamespacestd;classA{public:A(){std::cout <<"A: parameterless ctor"<< endl;}};classB{ A _a1,_a2;public:B(){std::cout <<"B: parameterless ctor"<< endl;}};intmain(){ B b;}
Answer:
We can clearly see that the member variables are initialized before the constructor of the object is called.
Question: In what order are the destructors called?
Answer:
Here we can clearly see that first the objects dtor is called only then are the the member objects dtors called
Default ctor
Now lets replace this line
with this line:
The following code won't complile because _a1 and _a2 won't be able to find their parameterless ctors'. Now this is quite a problem it seems that we can't have member objects in our class if they they don't have a default ctor. The solution to this problem is an initialization list.
Initialization list
As said before the member objects are initialized before the constructor of the object is called. But with init lists we can pass values to the objects right before entering the ctor. The syntax is:
Lets look at an example
Here we can see that even thought _a1 and _a2 will be initialized before entering our ctor, now we have control with what to initialize them.
This solves another problem because constant variables must be assigned a value at the time of the declaration without init list we wouldn't have been able to have a const variable as a member variable in our class, but now we can.
A(int a) { std::cout << "A: ctor with one param\n"; }
B(int i): var_to_init(value_to_give_ctor){
#include <iostream>
using namespace std;
class A {
public:
A(int a) { cout << "A (" << a << ") " << endl; }
};
class B {
A _a1,_a2;
public:
B(int i):_a1 (i), _a2(2*i){
cout << "B cons" << std::endl;
}
};
int main() {
B b{2};
}