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.

See also  5 Ways to Improve Customer Experience

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