You are on page 1of 20

CHAPTER 8

Constructors and Destructors


8.1 INTRODUCTION
One of the aims of C++ is to introduce user-defined data types such as class, that has all the fea-
tures very similar to the built-in data types such as int and float. In the case of built-in data types,
we can initialize an ordinary variable as:
int x = 12;
float y = 4.35;
Here x and y are built-in int and float data types and their values are initialized by assigning the
values 12 and 4.35 respectively.
We should also be able to initialize the user-defined data class type variable (object) in the
same way as a built-in data type int or float.
Moreover, when a variable of built-in data type goes out of the scope, the C++ compiler
destroys the variable automatically. In same way, the C++ compiler should be able to do that in the
case of user-defined class data type too. In the case of class, we have studied so far, such features
have not been explained.
However, C++ compiler provides a special member function called the constructor that
enables an object to be initialized itself when it is created. C++ also provides another member
function called the destructor that destroys the objects when they are no longer required and
releases the main memory. This chapter discusses these features of C++ in detail.
8.2 WHAT IS A CONSTRUCTOR?
A constructor is a special member function for automatic initialization of an object. Whenever an
object is created, the constructor will be implemented. A constructor function is used to initialize
the variable of whatever instance being created.
The special member function, constructor is called so because it constructs the values of
data members of the class.
8.2.1 Declaration and Definition
The under mentioned points should be followed while writing a constructor:
(a) The name of the constructor must be the same as that of its class name.
bpbonline all rights reserved
Part I Constructors and Destructors 191
(b) It is declared with no return type (not even void).
(c) It is normally declared in the public access within the class. Only in a rare case, it may be
declared with private access of a class.
The syntax of the constructor function is:
class user_defined_name
{
private:
data member;
public:
user_defined_name(); /* constructor */
/* declaration */
member functions;
}; // end of class declaration
user_defined_name :: user_defined_name()
/* definition of constructor */
{
_________
_________
}
Example 1
The program shown in Figure 8.1 describes a class student with private data members roll_numb
and age. The constructor student (int, int); is declared in the class student.
/* Program creating constructor */
#include <iostream.h>
class student
{
private:
int roll_numb;
int age;
public:
student (int, int); /* constructor declared */
void display(void) /* member function declaration */
{
cout << "\n Roll Number = " << roll_numb;
cout << "\n Age = " << age << endl;
}; /* end of fuction display definition */
}; /* end of class student declaration */
(Contd...)
bpbonline all rights reserved
192 Programming in C++ Part I
student :: student(int rn, int ag) /* constructor definition */
{
roll_numb = rn;
age = ag;
}
void main()
{
student ram(1200,19);
student mohan(1201,20);
cout << "\n Data of Student1 " << endl;
ram.display();
cout << "\n Data of Student2 " << endl;
mohan.display();
} /* end of program */
Figure 8.1(a) Programcreating constructor
The constructor student (int, int) is used to initialize the values of the objects ram and mohan
both of the class type student. The object ram is given the initial values for roll_numb as 1200 and
the age as 19. The object mohan is given the initial value for roll_numb as 1201 and the age as 20.
The output is shown in Figure 8.1(b). The function display() operates on the object ram using the
statement ram.display() and shows the data for ram. Similarly, the function display() operates on
the object mohan and shows the data for mohan.
Figure 8.1(b)
Typical run of
the program
given in Fig-
ure 8.1 (a)
Example 2
The program in Figure 8.2(a) gives a simple bank accounting system which uses the constructor to
initialize the bank balance and the rate of interest. It has different choices to select. Depending on
the choice, the program uses the function to perform the calculations.

Data of Student1

Roll Number = 1200
Age = 19

Data of Student2

Roll Number = 1201
Age = 20

bpbonline all rights reserved
Part I Constructors and Destructors 193
/* Program creating Bank deposit and Interest calculation system */
#include <iostream.h>
#include <stdio.h>
class bank_account
{
private:
float balance;
float int_rate;
public:
bank_account(); /* constructor declared */
void amt_deposit();
void amt_withdraw();
void compound_int();
void get_balance();
void menu();
}; /* end of class bank_account declaration */
bank_account :: bank_account() /* constructor definition */
{
cout << "\n Enter initial bank balance: " << endl;
cin >> balance;
cout << "\n Enter current rate of interest: " << endl;
cin >> int_rate;
}
/* Function amt_deposit() definition */
void bank_account :: amt_deposit()
{
float amount;
cout << "\n Enter the amount of deposit: " << endl;
cin >> amount;
balance = balance + amount;
cout << "\n Your present balance = " << balance << endl;
}
/* Function amt_withdraw() definition */
void bank_account :: amt_withdraw()
{
float amount;
cout << "\n How much money do you want to withdraw?" << endl;
cin >> amount;
if (amount <= balance)
{
balance = balance - amount;
cout << "\n amount drawn by you = " << amount << endl;
cout << " Your current balance = " << balance << endl;
}
else
(Contd...)
bpbonline all rights reserved
194 Programming in C++ Part I
cout << "\n Sorry, withdrawl not allowed, balance inadequate";
}
/* Function compound_int() definition */
void bank_account :: compound_int()
{
float interest;
interest = balance * int_rate;
balance = balance + interest;
cout << "\n Total interest amount = " << interest << endl;
cout << " Total amount = " << balance << endl;
}
/* Function get_balance() definition */
void bank_account :: get_balance()
{
cout << "\n Current balance = " << balance << endl;
}
/* Function menu() definition */
void bank_account :: menu()
{
cout << " \n ENTER YOUR CHOICE " << endl;
cout << "d --> amount deposited " << endl;
cout << "w --> amount withdrawl " << endl;
cout << "c --> compound interest calculation " << endl;
cout << "g --> getting display of bank balance " << endl;
cout << "q --> quit " << endl;
cout << " Select your option please \n";
}
void main()
{
class bank_account acct;
char ch;
acct.menu();
while ((ch = getchar()) != q)
{
switch (ch)
{
case d :
acct.amt_deposit();
break;
case w :
acct.amt_withdraw();
break;
case c :
acct.compound_int();
break;
(Contd...)
bpbonline all rights reserved
Part I Constructors and Destructors 195
case g :
acct.get_balance();
break;
}/* end of switch statement */
} /* end of while loop */
} /* end of main() block */
Figure 8.2(a) Programassigning initial data to the data members of a class using a constructor
Figure 8.2(b)
Typical run of
the program
given in Fig-
ure 8.2(a) for
choice d
Figure 8.2(c)
Typical run of
the program
given in Fig-
ure 8.2(a) for
the choice w

Enter initial bank balance:
1000

Enter current rate of interest:
.1

ENTER YOUR CHOICE
d --> amount deposited
w --> amount withdrawl
c --> compound interest calculation
g --> getting display of bank balance
q --> quit
Select your option please
d

Enter the amount of deposit:
1000

Your present balance = 2000
Enter initial bank balance:
2000

Enter current rate of interest:
.1

ENTER YOUR CHOICE
d --> amount deposited
w --> amount withdrawl
c --> compound interest calculation
g --> getting display of bank balance
q --> quit
Select your option please
w

How much money do you want to withdraw?
1800

amount drawn by you = 1800
Your current balance = 200
bpbonline all rights reserved
196 Programming in C++ Part I
Figure 8.2(d)
Typical run of
the program
given in Fig-
ure 8.2(a) for
the choices w
and g
Figure 8.2(e)
Typical run of
the program
given in Fig-
ure 8.2(a) for
the choice c
De fa ult C onstruc tors
The default constructor is a special member function which initializes the data members with no
arguments. Default constructors may be explicitly written in a program.
The syntax of the default constructor function is:
class user_defined_name
{
private:
data member;
(Contd...)

Enter initial bank balance:
200

Enter current rate of interest:
.1

ENTER YOUR CHOICE
d --> amount deposited
w --> amount withdrawl
c --> compound interest calculation
g --> getting display of bank balance
q --> quit
Select your option please
w

How much money do you want to withdraw?
1200

Sorry, withdrawl not allowed, balance inadequate
g

Current balance = 200

Enter initial bank balance:
200

Enter current rate of interest:
.1

ENTER YOUR CHOICE
d --> amount deposited
w --> amount withdrawl
c --> compound interest calculation
g --> getting display of bank balance
q --> quit
Select your option please
c

Total interest amount = 20
Total amount = 220
g

Current balance = 220
bpbonline all rights reserved
Part I Constructors and Destructors 197
public:
user_defined_name(); /* constructor declaration */
};
user_defined_name :: user_defined_name(){} /* definition
of constructor without any arguments*/
The following two types of declarations of default constructors are allowed in C++.
Typ e 1
/* Program segment creating default constructor */
#include <iostream.h>
class student
{
private:
int roll_no;
int age;
char sex;
public:
student() {} /* default constructor */
void get_data(); /* member function declaration */
void show (); /* member function declaration */
}; /* end of class definition */
Typ e 2
/* Program segment creating default constructor */
#include <iostream.h>
class student
{
private:
int roll_no;
int age;
char sex;
public:
student(int = 0) {} /* default constructor */
void get_data(); /* member function declaration */
void show (); /* member function declaration */
}; /* end of class definition */
bpbonline all rights reserved
198 Programming in C++ Part I
A default constructor accepts no parameters. The default constructor for class A is A ::
A(). If no such constructor is defined, then the compiler supplies a default constructor.
The statement such as A a; invokes the default constructor of the compiler to create the
object a.
8.2.2 Special Characteristics
The constructor functions have some special characteristics. These are as follows:
(a) Constructors functions should be declared in the public section.
(b) They are invoked automatically when the objects are created.
(c) They do not have return types, not even void and therefore, they can not return values.
(d) They make implicit calls to the operators new and delete when memory allocation and
cancellation respectively are required.
When a constructor is declared for a class, initialization of the class objects becomes
mandatory.
8.2.3 Parameterized Constructors
The constructors that can take arguments are called parameterized constructors. The program
shown in Figure 8.3(a) is similar to the program shown in Figure 8.1(a) except that the constructor
arguments have been parameterized.
/* Program creating parameterized constructor */
#include <iostream.h>
class student
{
private:
int roll_numb;
int age;
public:
student (int rn, int ag); /* parameter constructor */
/* void display(void) /* member function declaration */
{
cout << "\n Roll Number = " << roll_numb;
cout << "\n Age = " << age << endl;
}; /* end of fuction display definition */
}; /* end of class student declaration */
student :: student(int rn, int ag) /* constructor definition */
(Contd...)
bpbonline all rights reserved
Part I Constructors and Destructors 199
{
roll_numb = rn;
age = ag;
}
void main()
{
student ram(1200,19);/* implicit call */
student mohan = student(1201,20);/* explicit call */
cout << "\n Data of Student1 " << endl;
ram.display();
cout << "\n Data of Student2 " << endl;
mohan.display();
} /* end of program */
Figure 8.3(a) Programsegment creating a parameterized constructor
Figure 8.3(b)
Typical run of
the program
given in Fig-
ure 8.3 (a)
When a constructor is parameterized, we must provide appropriate arguments to the con-
structor functions.
Pa ssing Initia l Va lue s a s Arg ume nts
When a constructor is parameterized, the object declaration without parameter may not work. For
example, student ram where ram is an object of the class type student will not work. We
must pass the initial values as arguments to the constructor function when an object is declared.
This can be done in two ways:
(a) By implicit call
(b) By explicit call
By Implicit Call. The implicit call is implemented as follows:
student ram(1200,19);/* implicit call */
In the above statement student is a parameterized construct and the initial value of the object
ram is having the initial values roll_num as 1200 and age as 19. This method is also called the
shorthand method, and is used very often as it is shorter, looks better and easy to implement.

Data of Student1

Roll Number = 1200
Age = 19

Data of Student2

Roll Number = 1201
Age = 20
bpbonline all rights reserved
200 Programming in C++ Part I
By Explicit Call The following statement illustrates the explicit call for the parameterized con-
structor:
student mohan = student(1201,20); /* explicit call */
The above statement creates a student object mohan and passes the initial values for roll_numb as
1201 and age as 20.
A class constructor has the same name as its class. You may have more than one con-
structor with the same name, provided each has its own signature or arguments list.
8.2.4 Copy Constructors
Copy constructors are used whenever an object of a class needs to be created temporally. Copy
constructors are used to initialize an object by another object of a similar class.
The syntax of the copy constructor is:
class_name :: class_name (class_name &ptr);
Exa mp le 3
The following program segment represents the copy constructor for the user defined class Y.
Y :: Y(Y &ptr)
where ptr is the pointer to a class object Y.
Exa mp le 4
The copy constructor may be used in the following syntax using a const keyword:
class_name::class_name (const class_name &ptr)
For example, the user defined class Y and ptr is the pointer to a class object Y, then the sym-
bolic copy constructor is:
Y :: Y (const Y &ptr)
Exa mp le 5
The program shown in Figure 8.4(a) generates Fibonacci numbers using a copy constructor where
the copy constructor is defined within the class declaration itself. Fibonacci sequence is a
sequence of numbers which is equal to the sum of the two preceding numbers. The beginning of
the sequence appears as:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, etc.
The copy constructor takes an object of its own class as argument and produces such an
object. It does not return a function value.
bpbonline all rights reserved
Part I Constructors and Destructors 201
/* Program demonstrating copy constructor */
/* declared within the class */
#include <iostream.h>
class fib
{
private:
int f0,f1,fibc;
public:
fib() /*constructor definition */
{
f0 = 0;
f1 = 1;
fibc = f0 + f1;
}
fib (fib &ptr) /* copy constructor declaration */
{
f0 = ptr.f0;
f1 = ptr.f1;
fibc = ptr.fibc;
}
void diff() /* increment calculation */
{
f0 = f1;
f1 = fibc;
fibc = f0 + f1;
}
void display()
{
cout << fibc << \t;
}
}; /* end of class fib */ void main(void)
{
cout << "\n Fibonacci Numbers \n" << endl;
fib number;
for ( int i = 0; i < 10 ; ++i)
{
number.display();
number.diff();
}
} /* end of program */
Figure 8.4(a) Programgenerating Fibonacci series using a copy constructor
bpbonline all rights reserved
202 Programming in C++ Part I
Figure 8.4(b)
Typical run of
the program
given in Fig-
ure 8.4 (a)
Exa mp le 6
The program shown in Figure 8.5(a) generates a series of Fibonacci numbers using copy con-
structor. The copy constructor is defined outside the class declaration using a scope operator (::).
The output of the program is shown in Figure 8.5(b).
/* Program demonstrating copy constructor */
/* using scope operator (::) */
#include <iostream.h>
class fib
{
private:
int f0,f1,fibc;
public:
fib(); /*constructor declaration */
fib (fib &ptr); /* copy constructor declaration */
void diff(); /* increment calculation */
void display();
}; /* end of class fib */
fib :: fib() /* constructor definition */
{
f0 = 0;
f1 = 1;
fibc = f0 + f1;
}
fib :: fib (fib &ptr) /* copy constructor definition */
{
f0 = ptr.f0;
f1 = ptr.f1;
fibc = ptr.fibc;
}
void fib :: diff()
{
f0 = f1;
f1 = fibc;
fibc = f0 + f1;
}
(Contd...)

Fibonacci Numbers

1 2 3 5 8 13 21 34 55 89

bpbonline all rights reserved
Part I Constructors and Destructors 203
void fib :: display()
{
cout << fibc << \t;
}
void main(void)
{
cout << "\n Fibonacci Numbers \n " << endl;
fib number;
for (int i = 0; i < 10; ++i )
{
number.display();
number.diff();
}
} /* End of Program */
Figure 8.5(a) Programgenerating Fibonacci series using a copy constructor
Figure 8.5(b)
Typical run of
the program
given in Fig-
ure 8.5 (a)
8.2.5 Constructors with Default Arguments
It is possible to define constructors with arguments having default values. For example, the fol-
lowing constructor declared as complex() can be defined as shown below:
complex(float real, float imag = 0);
The default value of the argument imag is zero. When we write the following statement:
complex c(5.0);
it assigns the value 5.0 to the real variable and 0.0 to the imag (by default).
In case we write the following statement:
complex c(2.0, 3.0);
it assigns 2.0 to real and 3.0 to imag. Thus the actual arguments, when specified, override the
default value.
Diffe re nc e b e twe e n a De fa ult C onstruc tor a nd De fa ult Arg ume nt C onstruc tor
The default constructor is represented as A :: A() where A is the user defined class. The default
argument constructor is represented as A :: A( int i = 0). The default argument con-
structor can be called with either one argument or no arguments. When called with no arguments,
it becomes a default constructor.

Fibonacci Numbers

1 2 3 5 8 13 21 34 55 89

bpbonline all rights reserved
204 Programming in C++ Part I
An object declared as a constructor can be created and destroyed dynamically using the
memory allocation operators new and delete.
Exa mp le 7
The program shown in Figure 8.6(a) demonstrates initialization of the default constructor member
function. The class object student contains data members such as students name, roll number and
sex. These are initialized with the default argument values. The output is shown in Figure 8.6(b).
/* Program demonstrating initialization of default constructor */
#include <iostream.h>
class student
{
private:
char name[30];
int roll_no;
char sex;
public:
student(); /* constructor declaration */
void display();
}; /* end of class student */
student :: student() /* default constructor definition */
{
name[0] = 0;
roll_no = 0;
sex = \0;
}
void student :: display()
{
cout <<" \n student name = " << name << endl;
cout << "\n student roll no. =" << roll_no << endl;
cout << "\n student sex = " << sex << endl;
}
void main(void)
{
student z;
cout << "\n Display of default constructor data " << endl;
z.display();
} /* End of Program */
Figure 8.6(a) Programdemonstrating initialization of the default constructor
bpbonline all rights reserved
Part I Constructors and Destructors 205
Figure 8.6(b)
Typical run of
the program
given in Fig-
ure 8.6 (a)
8.3 DESTRUCTORS
A destructor is a function which gets executed as and when an instance of the class to which it
belongs goes out of existence. Thus the function destructor executes automatically when an object
of a class is destroyed.
8.3.1 Destructor Function Definition
The following points should be kept in mind while defining and writing the syntax for the
destructor function.
(a) A destructor function must be declared with the same name as that of the class to which it
belongs. But the first character of the destructor name must begin with a tilde (~).
(b) A destructor function is declared with no return types specified (not even void).
(c) A destructor function must have public access in the class declaration.
Keeping in mind the above points, the general syntax of the destructor function is as follows:
class user_defined_name
{
private:
data member;
public:
user_defined_name(); /* constructor declaration */
~user_defined_name(); /* destructor declaration */
member functions;
};
user_defined_name :: ~user_defined_name() /* definition
of destructor */
{
_________
}

Display of default constructor data

student name =

student roll no. =0

student sex =

bpbonline all rights reserved
206 Programming in C++ Part I
Exa mp le 8
The program shown in Figure 8.7(a) demonstrates the use of the destructor function in the bank
accounting system. The program is similar to that given in Figure 8.2(a) except that the destructor
function is also declared and defined. The output of the program is shown in Figure 8.7(b). In the
output of this program, [Figure 8.7(b)] you will notice that the destructor function comes into
/* Program using constructors and destructors */
/* creating Bank deposit and Interest calculation system */
#include <iostream.h>
#include <stdio.h>
class bank_account
{
private:
float balance;
float int_rate;
public:
bank_account(); /* constructor declared */
~bank_account(); /* destructor declared */
void amt_deposit();
void amt_withdraw();
void compound_int();
void get_balance();
void menu();
}; /* end of class bank_account declaration */
bank_account :: bank_account() /* constructor definition */
{
cout << "\n Enter initial bank balance: " << endl;
cin >> balance;
cout << "\n Enter current rate of interest: " << endl;
cin >> int_rate;
}
bank_account :: ~bank_account() /* destructor definition */
{
cout << "\n Details of bank_accounts deleted " << endl;
}
/* Function amt_deposit() definition */
void bank_account :: amt_deposit()
{
float amount;
cout << "\n Enter the amount of deposit: " << endl;
cin >> amount;
balance = balance + amount;
cout << "\n Your present balance = " << balance << endl;
}
(Contd...)
bpbonline all rights reserved
Part I Constructors and Destructors 207
/* Function compound_int() definition */
void bank_account :: compound_int()
{
float interest;
interest = balance * int_rate;
balance = balance + interest;
cout << "\n Total interest amount = " << interest << endl;
cout << " Total amount = " << balance << endl;
} /* Function amt_withdraw() definition */
void bank_account :: amt_withdraw()
{
float amount;
cout << "\n How much money do you want to withdraw?" << endl;
cin >> amount;
if (amount <= balance)
{
balance = balance - amount;
cout << "\n amount drawn by you = " << amount << endl;
cout << " Your current balance = " << balance << endl;
}
else
cout << "\n Sorry, withdrawl not allowed, balance inadequate"
<<endl;
}
/* Function get_balnce() definition */
void bank_account :: get_balance()
{
cout << "\n Current balance = " << balance << endl;
}
/* Function menu() definition */
void bank_account :: menu()
{
cout << " \n ENTER YOUR CHOICE " << endl;
cout << "d --> amount deposited " << endl;
cout << "w --> amount withdrawl " << endl;
cout << "c --> compound interest calculation " << endl;
cout << "g --> getting display of bank balance " << endl;
cout << "q --> quit " << endl;
cout << " Select your option please \n";
}
void main()
{
class bank_account acct;
char ch;
acct.menu();
(Contd...)
bpbonline all rights reserved
208 Programming in C++ Part I
while ((ch = getchar()) != q)
{
switch (ch)
{
case d :
acct.amt_deposit();
break;
case w :
acct.amt_withdraw();
break;
case c :
acct.compound_int();
break;
case g :
acct.get_balance();
break;
}/* end of switch statement */
} /* end of while loop */
} /* end of main() block */
Figure 8.7(a) Programdemonstrating use of destructors and constructors in a bank deposit and
interest calculation system
operation when you select q (for quit). The message "Details of bank_accounts deleted" appears
because of the execution of the destructor function when the object is destroyed.
The destructor should clean up any debris, so it actually serves a constructive purpose.
Figure 8.7(b)
Typical run of
the program
given in Fig-
ure 8.7(a)

Enter initial bank balance:
1000

Enter current rate of interest:
.1

ENTER YOUR CHOICE
d --> amount deposited
w --> amount withdrawl
c --> compound interest calculation
g --> getting display of bank balance
q --> quit
Select your option please
g

Current balance = 1000
q

Details of bank_accounts deleted
bpbonline all rights reserved
Part I Constructors and Destructors 209
8.3.2 Use of Destructor Function
The primary use of the destructor function is to release memory space when an object of a class is
no longer in use.
TEST PAPER
Time: 3 Hrs
Max Marks: 100
Answer the following questions.
1. State true or false:
(a) Constructors, like other member functions, can be declared anywhere in the class.
(b) Constructors do not return any value.
(c) A constructor that accepts no parameter is known as the default constructor.
(d) A class must have at least one constructor.
(e) Destructors never take any argument.
2. Define a constructor. Is it mandatory to use constructors in a class? In what way a con-
structor is different from an automatic initialization?
3. Give the rules governing the declaration of a constructor.
4. Write an object oriented program in C++ that prints the factorial of a given number using
a constructor and a destructor member function.
5. Write an object oriented program in C++ to find the sum of the following series using a
constructor member function:
(a) sum = 1
2
+ 2
2
+ 3
2
+ 4
2
+ ... + n
2
(b) sum = 1 + 3 + 5 + .....+ 2n + 1
6. Describe the importance of destructors.
7. Can we have more than one constructor in a class? If yes, explain the need for such a sit-
uation.
8. Write a short note on the following:
(a) Copy constructors
(b) Default constructors
bpbonline all rights reserved