Classes and Objects with Constructors/Destructors: Default, Parameterize and Copy Constructor

Get unlimited access to the best preparation resource for GATE : fully solved questions with step-by-step explanation- practice your way to success.

Download PDF of This Page (Size: 176K)

Image of Default Constructor

Image of Default Constructor

Image of constructor

Image of Constructor

Default Constructor

  • A constructor that accepts no parameter is called default constructor.

  • If no such constructor is defined, then the compiler supplies a default constructor.

  • In that case, it is called nothing-to-do constructor.

Parameterize Constructors

The constructors that can take arguments are called parameterized constructors.

Chart8.txt

When the object is created, we must supply arguments to the constructor function. This can be done in two ways:

  • By calling the function explicitly

  • By calling the function implicitly

The first call is implemented as follows:

student S1 = student (1, 70).

The second call is implemented as follows:

student S1 (1, 70).

The second method is used very often as it is shorter.

Copy Constructor

A copy constructor takes a reference to an object of the same class as itself as an argument. Consider the following program segment:

Chart9.txt

The above program has both parameterized and copy constructor. The statement

student S1 (1, 75).

Calls the parameterized constructor and assigns 1 to run and 75 to total. The statement

student S2 (S1).

uses copy constructor and initializes an object S2 from another object S1. Another form of the statement is

student S2 = S1.

The process of initialization through a copy constructor is known as copy initialization.

Note that the statement

S2 = S1.

does not invoke the copy constructor. However, it simply assigns the value of S1 to S2, member by member.

Developed by: