Types of Constructors
5A. Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters.
// Cpp program to illustrate the// concept of Constructors#include <iostream.h>classconstruct{public:inta, b;// Default Constructorconstruct(){a = 10;b = 20;}};voidmain(){// Default constructor called automatically// when the object is createdconstruct c;cout <<"a: "<< c.a << endl <<"b: "<< c.b;}Output:a: 10 b: 205B. Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object.
// CPP program to illustrate// parameterized constructors#include<iostream.h>classPoint{private:intx, y;public:// Parameterized ConstructorPoint(intx1,inty1){x = x1;y = y1;}intgetX(){returnx;}intgetY(){returny;}};voidmain(){// Constructor calledPoint p1(10, 15);// Access values assigned by constructorcout <<"p1.x = "<< p1.getX() <<", p1.y = "<< p1.getY();}output:p1.x = 10, p1.y = 15
Paramaterized Constructor video: 5minuteshttps://www.youtube.com/watch?v=2LxU7vroRj0