Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use new Type() or just Type() for calling a constructor

Both syntaxes are equivalent (at least I suppose they are).

let o1 = new Object()

or

let o2 = Object()

Which way do you use more often? What about readability issues?

like image 770
Stringer Avatar asked Dec 01 '09 23:12

Stringer


People also ask

Can constructor be called without new?

Constructors requires the use of the new operator to create a new instance, as such invoking a class without the new operator results in an error, as it's required for the class constructor to create a new instance.

Can I use new in constructor?

Constructor functions or, briefly, constructors, are regular functions, but there's a common agreement to name them with capital letter first. Constructor functions should only be called using new .

Is a constructor called using the new operator?

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator.

How do you call a constructor?

Invoking a constructor from a method No, you cannot call a constructor from a method. The only place from which you can invoke constructors using “this()” or, “super()” is the first line of another constructor.


1 Answers

I feel like omitting "new" is a bit more functional, so that's my preference. I like that you can treat a constructor just like any other function returning an instance of a type.

like image 175
kvb Avatar answered Oct 15 '22 19:10

kvb