• In C++ constructor is a special type of member function of a class which initializes objects of a class.
  • Constructor is automatically called when object is created in C++.
  • It does not have any return type because it is special member function of the class.
  • In public section of class and it has same name as the class itself.
  • Copy and parameterized constructors have input arguments, by default constructors don’t have input argument however.
  • C++ compiler generates a default constructor for object, if we do not specify a constructor.
  • In constructor there are three types, they are default constructor, parameterized constructor, copy constructor.

Default Constructor

  • It is the constructor which has no parameters and doesn’t take any argument.

Sample Code

using namespace std;

class construct

{

public:

    int a, b;




    // Default Constructor

    construct()

    {

        a = 30;

        b = 40;

    }

};




int main()

{

    // Default constructor called automatically

    // when the object is created

    construct c;

    cout << "a: " << c.a << endl

         << "b: " << c.b;

    return 1;

}

Output

Parameterized Constructor

  • It is possible to pass arguments to constructors and these arguments help initialize an object when it is created typically.

Sample Code

using namespace std;

class Point

{

private:

    int x, y;




public:

    // Parameterized Constructor

    Point(int x1, int y1)

    {

        x = x1;

        y = y1;

    }




    int getX()

    {

        return x;

    }

    int getY()

    {

        return y;

    }

};




int main()

{

    // Constructor called

    Point p1(10, 15);




    // Access values assigned by constructor

    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();




    return 0;

}

 Output

Copy Constructor

  • It is a member function which initializes an object using another object of the same class.

Sample Code

using namespace std;

class point

{

private:

  double x, y;




public:

   

  // Non-default Constructor &

  // default Constructor

  point (double px, double py)

  {

    x = px, y = py;

  }

};




int main(void)

{




  // Define an array of size

  // 10 & of type point

  // This line will cause error

  point a[10];




  // Remove above line and program

  // will compile without error

  point b = point(5, 6);

}

Output

Categorized in: