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


Tip of the Day
Language: C++
Expertise: All
Jan 3, 2000

Avoid Redundant Parentheses in Object Instantiation

Although the following statements are semantically equivalent

 
  string * p = new string(); //with empty parentheses
  string * p = new string; //no parentheses

The second one is preferable for two reasons. First, the parentheses are redundant anyway because they do not contain any arguments. More importantly, programmers who use the first form are often inclined to use empty parenthesis when creating local automatic objects, as in:

 
  string s(); //probably and error

The programmer mistakenly assumed that this statement creates a local string object but it doesn't. In fact, this statement is interpreted as a declaration of a function named s, which returns a string object by value and takes no arguments. This is very different from the following:

 
  string s;  

This statement, on the other hand, creates an object named s of type string, which is what the programmer originally intended. As you can see, the bad habit of placing a redundant pair of empty parentheses when using new can be dangerous. Avoid it.

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