Avoid Redundant Parentheses in Object Instantiation

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.


Share the Post: