/    /  CPP- Types of Constructors

Types of Constructors

 

There are three types of constructors:   

   1. Default Constructor – The default constructor is the constructor that does not take an argument. There are no parameters.

   2. Parameterised constructor – These are constructors with parameters. Using this constructor, you can provide different values to data members of different objects, passing the relevant values as an argument.

   3. Copy Constructor – This is a special type of Constructors that takes an object as its argument, and is used to copy the

data member values of an object to another object.

 

Example Program:

#include<iostream>
using namespace std;
class A
{ 
 int i, j;
 public:
 A( ); // default Constructor declaration
 A(int x,int y=0); // Parameterized constructor declaration
 A(A& D); // copy constructor declaration
 void show(); // member function declaration
};
A :: A() // constructor definition
{ 
 i = 0;
 j = 0;
}
A::A(int x, int y) // parameterized constructor definition
{ 
 i = x;
 j = y;
}
A::A(A& D) // copy constructor definition
{ 
 i = D.i;
 j = D.j;
}
void A::show()
{ 
 cout<<"i = "<<i << endl;
 cout<<"j = "<<j << endl;
}
// objects E,F,G and H are used
int main( )
{ 
 A E;
 int m,n;
 cout<<"Enter two values: ";
 cin>>m>>n;
// m and n values knows at runtime only
 A F(m,n);
 A G(F); // copy constructor called
 cout<<"E details"<<endl;
 E.show();
 cout<<"F details"<<endl;
 F.show();
 cout<<"G details"<<endl;
 G.show();
 return 0;
}

 

Output: