What is Constructor

Constructor is a special member function which is used to initialize the data members into the object. Constructor is a special method which is called automatically when an object is created.

  • Constructor name must be same as the class name.
  • Constructor must not have any return type.
  • Constructor is called implicitly when any object is created.
  • C++ Constructor must be placed in the public section of the class.
  • When there is no constructor in any class, then the compiler adds a default constructor in the class.

Types of Constructor

Constructor in C++ are of following three types:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor

Default Constructor:

Default Constructor are referred to as those constructor which do not contains any arguments or any parameters.

Example:

// program to demonstrate the use of default Constructor
#include<iostream.h>
#include<conio.h>
class Student
  {
 public:
    Student()  // default Constructor
    {
    cout<<"\n I am a default Construtor";
     }
  };

void main()
 {
 clrscr();
 Student s; // object created and constructor is invoked implicitly
 getch();
 }