dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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.

 

 

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