Classes and Objects with Constructors/Destructors: Constructor with Default Arguments and Destructor

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

Download PDF of This Page (Size: 374K)

Image of default arguments with constructors

Image of Default Arguments

Constructor with Default Arguments

The constructor can be declared with default argument.

For example:

student (int run, int total = 0).

Here the default value of total is zero.

Then the statement

student S1 (2).

assigns the value 2 to run and 0 to total.

However, the statement

student S2 (3, 75).

assigns 3 to run and 75 to total. In this case actual parameter takes the priority over default parameter. All default values should be on the right side.

Consider the following statement

A (int = 0).

It has only one argument. It can be called in two ways.

A B.

A B (5).

In the first statement, no parameter is supplied. In the second statement, one parameter is supplied. When no parameter is supplied, it becomes a default constructor. When both the forms are used in a class (default constructor and constructor with one default argument), it causes ambiguity for a statement such as

A B (whether to call A () or A (int = 0)

Destructor

  • It is used to destroy the objects that have been created by a constructor. The destructor is a member function whose name is the same as the class name but is preceded by a tilde. For example, the destructor of the class student can be defined as

- student ().

  • It never takes any argument, nor does it return any value. It will be invoked by the compiler upon exit from the program (or function or block) to clean the storage. It is a good practice to declare destructor in a program because it releases memory space for future use.

Developed by: