What is a constructor in programming?

723 viewsOtherTechnology

I am still trying to wrap my head around the concept I learned in class a while ago. We learned briefly about constructors in JavaScript. Can someone please ELI5? Thank you!

In: Technology

18 Answers

Anonymous 0 Comments

Basically, a constructor is just a function inside the class that can take arguments and is used to create an object in return. 

What it will do in order is that it will first allocate/reserve the right amount of memory for the object (this step is often hidden away in languages like JavaScript, Java or Python). Then it will initialise the object with either default values or the arguments you provided to it. Finally, it will return you the initialised object so you can use it afterwards in other parts of your code.

Similarily, in some languages like C where you have to manually manage your memory, there’s also the concept of a destructor which is simply the opposite of a constructor, so a function that takes the object as argument and will free the memory used by that object so that it is available again to other parts of the program.

You are viewing 1 out of 18 answers, click here to view all answers.