Wednesday 17 February 2016

Constructor and problem of initialization in C++


  • Constructor is a member function of a class.
  • The name of constructor is same as the name of the class.
  • It has no return type, so the definition of constructor can not use the return keyword.
  • Normally, if we don't write return type of any function then by default its return type is considered as int.
  • But in case of constructor it has no return type.
  • It must be an instance member function, that is it can never be qualified with static keyword.

How to call constructor?
  • Constructor is implicitly invoked when as object is created.
  • Constructor is used to solve problem of initialization.
What is problem of initialization?
Okay, the answer to this question is the answer to the question " why is it called constructor? "
A constructor makes an object an object., this may sound crazy but yes this is true. As in our normal life we say "become a human" ( i.e. become a good person with good characteristics ). Similarly, the constructor makes an object as a good object.
Consider an example:
class
{
  private:
  int car_number;
  string color;
......
};
Now if we create an object to the class, then the instance member variables will have some garbage values into them and thus we can not point to a particular car. If we would have used a constructor to initialize the car_number and colour, then we can point to a particular car. Thus a constructor makes object as a perfect object. 
So we need to initialize the instance member variable at the time of creation of objects and that can be done by using the constructors.

Important topics in constructor:
  • Default constructor
  • Parametrized Constructor
  • Constructor overloading
  • Copy constructor.

1 comment: