+ 6
Why do we use constructor?
4 Answers
+ 6
We use contructor to pass some default values to variables inside our new variable. Let's say you have a class named "car", and when you create an object of that class, you want to specify things like "max speed", "type of car", "amount of wheels(?)" and so on. To make things quick, you do all this in a constructor, just like that: Car my_new_car = new Car(name, type, wheels);
this is the power of constructor, it just saved you 3 lines of code. You can make some math inside a constructor too. Let's say you have a constructor of a lamp. You send it some materials, a light bulb and some more things. When you send them, there are some things going inside a constructor that makes all of those things work together, No need for you to call some method every time cause contructor calls it when you initialize an object!
+ 5
Constructor is basically used to initialize the class variable at the time of creating the object.
If you do not explicitly define a constructor for a class, then a default constructor comes into role.
E.g.
class xyz
{
public xyz()
{
  // Initialize the variables over here.
 }
// Declare the variables over here.
}
+ 2
maybe an example from daily business: I just used the constructor inside my Database class, which fires my prepared statements. Within the constructor I create a new connection an initialise the connection string, which otherwise needs more rows of code for each statement... so, constructors are a cool thing;)
+ 1
constructor is special member function which can use for the initialise the variables. Constructor are automatically call when at the time of creating the object