Constructors in C++ – Features and Types

In this tutorial, we are going to understand about features of constructors, types of constructors, syntax with some examples in C++.

Constructor and its features:

  • Constructors are the special members of the class which initialize the object of class.
  • A constructor is automatically invoked at the creation of the object.
  • It is generally used to initialize variables.
  • It has the same name as of class.

It does not have any return type(i.e. void, int, etc).

Types of Constructor in C++:

  • Default constructor
  • Parameterized constructor
  • Copy constructor

Default Constructor

A constructor that doesn’t have parameters. It is invoked automatically and can carry default values. If we do not define constructor it will still define an empty constructor implicitly.

class A
{
public:
int a,b;
A()     //Default cosntructor
 {
 a=10;   //random values
 b=20;
 }
};
int main()
{
A obj;  //constructor invoked
cout<<"a= "<<obj.a<<endl;
cout<<"b= "<<obj.b<<endl;
return 0;
}

Output:

a= 10
b= 20

Parameterized Constructor in C++

When we can pass values to constructor it is called parameterized constructor. Passing values to the constructors are same as with functions. It is used to initialize variables in a class.

Class A
{
private:
int x,y;
public:
A(int a,int b) //Parameterized Constructor
 {
 x=a;
 y=b;
 }
};
int main()
{
A obj(10,20); //constructor called
cout<<"x= "<<obj.x<<endl; //accessing value by constructor
cout<<"y= "<<obj.y<<endl;
}


Output:

x= 10
y= 20

Copy Constructor in C++

A copy constructor is used to copy the variable of one object into another object. It can be written as :

class_name(const class_name &old_obj);

class A{
private:
int a,b;
public:
A(int x,int y)
 {
 a=x;
 b=y;
 }
A(const A &obj1) //copy constructor
 {
 a=obj1.x;
 b=obj1.y;
 }
};
int main()
{
A obj1(10,20); //Normal constructor
cout<<obj1.a<<" "<<obj1.b<<endl;
A obj2(obj1); //copy constructor call
cout<<obj2.a<<" "<<obj2.b<<endl; 
return 0;
}

Output:

10 20
10 20

Recommended:

Constructors in C++

For suggestion and querry please comment below.

Leave a Reply