Composition and Init lists

Composition

Definition: Composition describes a class that references one or more objects of other classes in instance variables.

class Line {
  Point p1, p2;
};

C++

Java

Members are objects

Members are pointers

Construction

Question: In what order are the constructors called?

#include <iostream>
using namespace std;

class A {
public:
    A() { std::cout << "A: parameterless ctor" << endl; }
};

class B {
    A _a1,_a2;
public:
    B() { std::cout << "B: parameterless ctor" << endl;}
};

int main() {
    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.

Advantages of using initialization list

  • Faster – no need for default initializaiton

  • Safer – be sure that all components are ready.

  • Can initialize constants and reference variables.

  • Can initialize parent class.

Last updated