What are types of constructors in C++4 min read

Types of Constructors

A constructor can be classified into following types:

  1. Dummy constructor
  2. Default constructor
  3. Parameterized constructor
  4. Copy constructor
  5. Dynamic constructor

Dummy Constructor

When no constructors are declared explicitly in a C++ program, a dummy constructor is invoked which does nothing. So, data members of a class are not initialized and contains garbage values. Following program demonstrates a dummy constructor:

Output for the above program is as follows:

You can see that since age and branch are not initialized, they are displaying garbage values.

Default Constructor

A constructor which does not contain any parameters is called a default constructor or also called as no parameter constructor. It is used to initialize the data members to some default values. Following program demonstrates a default constructor:

Output for the above program is as follows:

Parameterized Constructor

A constructor which accepts one or more parameters is called a parameterized constructor. Following program demonstrates a parameterized constructor:

Output for the above program is as follows:

Copy Constructor

A constructor which accepts an already existing object through reference to copy the data member values is called a copy constructor. As the name implies a copy constructor is used to create a copy of an already existing object. Following program demonstrates a copy constructor:

Output for the above program is as follows:

In the above program you can see that there are two ways for calling a copy constructor. One way is to call the copy constructor by passing the object as a parameter (in case of s2). Other way is to directly assign an existing object to a new object (in case of s3).

Note: Copying an object through assignment only works during object declaration. After declaring an object, assignment just serves its basic purpose.

Dynamic Constructor

A constructor in which the memory for data members is allocated dynamically is called a dynamic constructor. Following program demonstrates dynamic constructor:

Input and output for the above program are as follows:

Take your time to comment on this article.

Leave a Comment