Why Initialization Lists in
Constructors?
The old method of
initializing variables, was as follows:
class monkey{
banananas
b; // yes I
know how to spell banana, I just forget when to stop.
tree *t;
monkey(banananas
x){
b = x;
t = new tree();
}
}
Nowadays you are told to
use Initialization Lists in this manner:
monkey(banananas x):b(x),t(new tree()){}
Where it looks like b(x),t(new tree()) is the same as b = x; t = new
tree();
It is not.
t = new tree();
causes a temporary anonymous variable to
be created.
anonymous variable = new tree();
then
t =
anonymous variable; // using the assignment overload.
finally destruct anonymous
variable.
Suppose that tree allocates
1 M of memory and then opens a file reads it.
Upon calling the
destructor, the file must be closed and the memory free'd.