The Uses of Fundamental Types’ Constructors

The Uses of Fundamental Types’ Constructors

You can initialize variables of fundamental types by invoking their constructor:

   int n = int();  /* zero initialized */   char c = char();  /* ditto */   short *ps = new short(0);  /* ps points at a zero-initialized short */ 

Apparently, the constructor-like syntax seems redundant; after all, you can use the traditional initialization syntax:

   int n = 0;     char c = 0;

So is it just an interesting bit of trivia? No, it isn’t. The constructor-initialization form is the only way to initialize dynamically allocated variables. Consider

   short *ps = new short(0);

Without the constructor initialization, ps would point to a short with an indeterminate value. More importantly, generic algorithms and containers rely on this form toprovide a uniform interface for fundamental types and user-defined typesalike. Thus, a vector can copy-construct its elements in exactlythe same way as a vector does.


Share the Post: