2

I do not know much about OO-languages, but from what I have seen, it seems most class-based OO-languages uses a keyword new (or something equivalent) to create an object. Prototype-based OO-languages like JavaScript even fake it.

From a viewpoint of keeping the syntax simple, why not leave out the new keyword and use only the constructor (typically of the same name as the class)?

Is there any semantic consideration involved in prefixing the constructor with a new keyword?

I have noticed that in Scala, if you define a case-class, you can simply use the constructor without a preceding new to create an object, while for other classes, you have to use new. I do not know the reason. I mention it simply because it may be related.

8
  • 5
    Did you have a look at Python? It works exactly the way you suggested - without the new keyword. I guess most languages using "new" as a keyword just inherited that from C++ for historical reasons.
    – Doc Brown
    Jan 3, 2015 at 9:40
  • In Delphi / Object Pascal you call the constructor directly: myClass := TMyClass.Create;
    – oɔɯǝɹ
    Jan 3, 2015 at 10:00
  • 1
    In C++ and JavaScript it's syntactically important. But even in languages where it could have been left out, don't you think it makes for more descriptive (self-documenting) code? If I write List() is it creating a list, or is it listing something (noun or verb)? If I write new List() the ambiguity goes away.
    – Hey
    Jan 3, 2015 at 10:27
  • In Java, it is possible for class X to contain a method X that cannot be distinguished by its parameter list from an X constructor. "new" distinguishes object creation from method invocation. Jan 3, 2015 at 10:52
  • @PatriciaShanahan I guess you could avoid that with explicit this, couldn't you? I think "new distinguishes object creation from method invocation" is exactly the point, though... not necessarily just for the compiler/interpreter, but also for the developer.
    – Hey
    Jan 3, 2015 at 11:53

1 Answer 1

3

As far as I know, it's simply a question of C++ having this syntax (and it needed some syntax because the language was not strong enough to support implementing new T(); at that time as a library) and then inherited. From memory, Java inherited it from C++, JavaScript picked it up from Java, and so did C#. Since then, it seems to have become pretty standard.

Fundamentally, it's no different to using curly braces to denote scope- it was inherited from a common ancestor.

Not the answer you're looking for? Browse other questions tagged or ask your own question.