Constructor Initializer: Understanding it from Assemble Language

Overview

I try to explain the constructor initializer from the assemble language level and some key facts about constructor initializer would be highlighted too.

Constructor Initializer: Why do We Need it

The key fact about constructor initializer is the initializing happens before the execution of the constructor body as shown in the following code.

#include

class Tester {
public:
	Tester() : a(5), b(-5) {
		printf("Start of Tester() body :\n a = %d, b = %d\n", a, b);
		a = -11, b = 11;
		printf("End of Tester() body :\n a = %d, b = %d\n", a, b);
	}

private:
	int a;
	int b;
};

int main() {
	Tester tt;
	return 0;
}
/*
 * The outputs:
 *
 *  Start of Tester() body
 *  a = 5, b = -5
 *  End of Tester() body :
 *  a = -11, b = 11
*/

People get confused about the difference between them is because the assignment would override the values anyways, then why do we need the initializing? Some of the reasons are listed:

  1. constant variable has to be initialized in the constructor initializer because it is not allowed to do assignment
  2. reference type variable has to be initialized in the constructor initializer too because it has to be bind to some other variable

And another set of facts and suggestions about constructor initializer  are:

  1. The order of initializing does not matter, that is, the constructor initializer  itself does not influence the order in the constructor initializer  it only provide the initial values, the order in the constructor initializer  does not represent the real order of initializing.
  2. It is suggested to use constructor initializer  as much as you can

Constructor Initializer:  Understanding it from Assemble Language

People get confused about the constructor initializer  because they might not clearly distinguish the difference between initializing and assignment. From the view of assemble language. Assignment will involve an assemble instruction like Store 5 mem[0x555] meaning that store the value 5 in the memory location at mem[0x555]. But this instruction has nothing to do with the initial value at mem[0x555] before this instruction execution.

And regarding initializing, its responsibility is to put the specific value in that memory location, the assemble code might something different and depends on different compiler behavior and implementations.

So the conclusion is that, before the constructor body execution, all the member variables already have some initial value which either you specify in the constructor initializer or the default values are given. The following things in the constructor body are all about assigning and has nothing to do with initializing.

Summary

In this post I explained the constructor initializer from the assemble language level and some key facts about constructor initializer would be highlighted too. Please feel free to share your comments.

Written on December 10, 2014