Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Oct 6, 1999



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 to provide a uniform interface for fundamental types and user-defined types alike. Thus, a vector <int> can copy-construct its elements in exactly the same way as a vector<string> does.
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date