Why does the new operator exist in modern languages such as C# and Java? Is it purely a self documenting code feature, or does it serve any actual purpose?
For instance the following example:
Class1 obj = new Class1();
Class1 foo()
{
return new Class1();
}
Is as easy to read as the more Pythonesque way of writing it:
Class1 obj = Class1();
Class1 foo()
{
return Class1();
}
EDIT: Cowan hit the nail on the head with the clarification of the question: Why did they choose this syntax?
Class1 obj = Class1();
In C# and Java, you need the "new" keyword because without it, it treats "Class1()" as a call to a method whose name is "Class1".
The usefulness is of documentation - it's easier to distinguish object creations from method invocations than in Python.
The reason is historic, and comes straight from the C++ syntax. In C++, "Class1()" is an expression creating a Class1 instance on the stack. For instance: vector a = vector(); In this case, a vector is created and copied to the vector a (an optimizer can remove the redundant copy in some cases).
Instead, "new Class1()" creates a Class1 instance on the heap, like in Java and C#, and returns a pointer to it, with a different access syntax, unlike Java and C++. Actually, the meaning of new can be redefined to use any special-purpose allocator, which still must refer to some kind of heap, so that the obtained object can be returned by reference.
Moreover, in Java/C#/C++, Class1() by itself could refer to any method/function, and it would be confusing. Java coding convention actually would avoid that, since they require class names to start with a upper case letter and method names to start with a lower case one, and probably that's the way Python avoids confusion in this case. A reader expects "Class1()" to create an object, "class1()" to be a function invocation, and "x.class1()" to be a method invocation (where 'x' can be 'self').
Finally, since in Python they chose to make classes be objects, and callable objects in particular, the syntax without 'new' would be allowed, and it would be inconsistent to allow having also another syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With