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.

See also  11 Effective Keyword Research Tools and Techniques

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist