Friday 24 February 2012

Can one constructor of a class be called by another constructor of the same class for initializing the this object? | C++

a No, not possible. Let's understand it with the help of an example.
Take a human class. Now, we want our constructor Human::Human(char) to call another constructor of the same class, say Human: :Human(char,  int), in order that

Human::Human(char, int) would help to initialize the this object. Unfortunately, there is no way to do this in C++.
It always occur in its specific form and not the way a user wants. For example, the line Human(h, 0); does not call Human::Human(char, int) on the this object. Instead it calls Human::Human(char, int) to initialize a temporary, local object (not this), then it immediately destructs that temporary object when control flows over the ;.
Example:

If there is no default parameter for combining the two constructors, then there is a need of sharing of their common code in a private init() member function:
Another example: