Parentheses after type name in new: is there a difference?
Hi everyone! I started learning C++ and came across a strange thing with the `new` operator. When I allocate memory for an object, I see two options:\n\n```cpp\nint* p1 = new int; // without parentheses\nint* p2 = new int(); // with parentheses\nint* p3 = new int(42); // with a value\n```\n\nOr for classes:\n```cpp\nMyClass* obj1 = new MyClass;\nMyClass* obj2 = new MyClass();\nMyClass* obj3 = new MyClass(42);\n```\n\nAll three options seem to work, but I noticed that in some cases `new int` and `new int()` behave differently. For example, I read that for built-in types (int, double, etc.) `new int()` initializes memory to zero, while `new int` leaves garbage. Is this true?\n\nAnd what about user-defined classes? Is there a difference between `new MyClass` and `new MyClass()` if the class has a constructor?
No answers yet.
Log in to leave an answer
Blogs