+ 6

What is a constructor.????

please explain me about constructors as I am finding it hard to understand....

24th Jan 2018, 3:44 PM
Anmol Batra
Anmol Batra - avatar
3 Answers
+ 4
How well do you understand classes and objects? If you understand them well, then this won’t take very long. If not go below the ==== line then come back up. A constructor is a method that gets called once when an object is made. The syntax depends on the language, so I won’t get into that. It is basically just what code you want to run when you create an object. ==================== You can think of an class as defining what something is, what it can do, anything like that. Let’s say you have a program that is supposed to simulate animals and you want it to involve cats. Before you can make any cats, you have to tell the program what a cat is. That is what happens when you make a class, you tell the program what that thing is. Next, it is time to declare an object. A class is like a data type, so an object is like a variable. It has all of the attributes defined in the class completely unique for itself. It’s own age, name, whatever attributes you put in the class. When you declare an object, this is when the code in the constructor runs.
24th Jan 2018, 4:06 PM
Jacob Pembleton
Jacob Pembleton - avatar
+ 3
constructor is similar like normal function.but it used to initialize data members automatically when object of the class is created.. note: it constructs data member's memories in stack without calling it(automatically) when new object is created.. use: using construtors your required resources (variables with some initial value) are ready.. before u use it ...
24th Jan 2018, 4:01 PM
Somasundaram R
Somasundaram R - avatar
+ 3
constructor is actually called when an object is initialized and it's function is to allocate memory to object (ie,create an object ) So, basically a constructor is a function (or method) which creates an object when an object is declared
4th Feb 2018, 5:00 AM
Akshat Vira
Akshat Vira - avatar