C++ Constructors and Destructors

Constructor

A constructor is a special member function with the same name as its class name and is used to initialize the data members of the class. Constructor is invoked automatically when an object of a class is created. Constructor does not return any value not even void. Constructor must be defined in the public section.

Type of Constructor

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor
  • Default Argument Constructor
  • Dynamic constructor

Default Constructor

Whenever a class is defined without constructor definition, the compiler provides a default constructor to construct the objects of a class. This default constructor initializes all the data members with garbage values. However, to initialize the data members with valid values the default constructor needs to be defined explicitly. In such cases, the default constructor provided by the compiler is overridden.

Parameterized Constructor

When different objects need to be initialized with different values, a parameterized constructor can be defined. A parameterized constructor is a constructor that accepts one or more parameters at the time of declaration of objects and initializes the data members of the objects with these parameters.

Copy Constructors

The objects of a class can be initialized either with same values using default constructor or with different values using a parameterized constructor. However, a new object of a class can also be initialized with an existing object of the same class. For this, the compiler calls another constructor, known as the copy constructor. A copy constructor is a constructor that initializes a new object of a class with the values of an existing object of the same class.

Default Argument Constructor

The parameterized constructor that has all the default arguments can be considered as a default constructor since it can be invoked without arguments. This implies that if an object is declared without parentheses, all the data members are initialized with the default values. For example, a default argument constructor of the form time::time(int=10,int=20,int=30) can be called with zero or more arguments. If no argument is specified, it can be considered as a default constructor of the form time::time().

Dynamic constructor

A dynamic constructor is a constructor that allocates memory to the objects at the time of their construction using the new operator. Moreover, it enables the objects of different sizes to be allocated the required amount of memory and hence, save the memory space.