You are on page 1of 19

Constructors and Destructors 5.

CHAPTER 5

CONSTRUCTORS AND DESTRUCTORS

5.1 CONSTRUCTORS

A constructor is a special member function whose main operation is to allocate the


required resources such as memory and initialize the object of its class.
The constructor of a class is the first member function to be executed automatically
when an object of the class is created.
Syntax
class classname
{
Public:
classname ( ); // Constructor Prototype
};
classname :: classname ( )
{
// Constructor body definition
}
Similar to other members, the constructor can be defined either within, or outside the
body of a class. It can access any data member like all other member functions but cannot
be invoked explicitly and must have public status to serve its purpose. The constructor which
does not take arguments explicitly is called default constructor.
A constructor has the following characteristics
I It has the same name as that of the class to which it belongs.
I It is executed automatically whenever the class is instantiated.
I It does not have any return type.
I It is normally used to initialize the data members of a class.
I An object with a const cannot be used as a member of a union.
5.2 OOPs Programming

I It also used to allocate resources such as memory to the dynamic data members
of a class.
I They make implicit calls to the operators new and delete when memory allocation
is read.
I It should have public access within the class.
I It cannot be declared as static or const.
I Constructor cannot be virtual.
I They cannot be inherited, through the derived class can call the base class
const.
// Constructors
# include <iostream.h>
class sample
{
int a;
Public:
sample ( );
void show ( )
{
cout << a; }
};
sample : : sample ( )
{
cout << “\n This is a constructor”;
a = 100;
}
main ( )
{
sample S;
S.show ( );
}
Output
This is a constructor 100.
Constructors and Destructors 5.3

5.2 PARAMETERIZED CONSTRUCTORS

Constructors can be invoked with arguments. The argument list can be specified within
braces similar to argument-list in the function constructors with arguments are called
parameterized constructors.

We must pass the intial values as arguments to the constructor function when object is
declared.

This can be done in two ways.

I By calling the constructor explicitly.

I By calling the constructor implicitly.


eg.:
class sample
{
int a, b;
public:
sample (int x, int y);
---
---
};
sample :: sample (int x, int y)
{
a = x ; b = y;
}
eg.:
sample S = sample (2, 3); // explicit call;
sample S (2, 3); // implicit call;
// parameterized constructors
# include <iostream.h>
class sample
5.4 OOPs Programming

{
int a, b;
public:
sample (int, int); // Constructor declared
void display ( )
{
count << “a =” << a << endl;
count << “b =” << b << endl;
}
};
sample :: sample (int x, int y)
{
a = x ; b = y;
}
main ( )
{
sample S(2, 3); // implicit call
sample S2 = sample (4, 5); // explicit call
S1.display ( );
S2.display ( );
}
Output
a a=2
b=3
a=4
b=5

5.3 DESTRUCTOR

When an object is no longer needed it can be destroyed. A class can have another
special member function called the destructor, which is invoked when an object is destroyed.
Constructors and Destructors 5.5

Like a constructor, destructor is a member function whose name is the same as the class
name but is preceded by a tilde (~).
It is invoked automatically to reclaim all the resources allocated to the object when the
object goes out of scope and is no longer needed.
Syntax
class classname
{
public:
~ classname ( ); // destructor prototype
};
classname :: ~ classname ( )
{
// destructor body definition
}
Characteristics of Destructor
I A class cannot have more than one destructor.
I A destructor must be declared in the public section of a class so that it is
accessible to all its users.
I It has no return type.
I It is incorrect to even declare a void return type.

// implementation of destructors
# include <iostream.h>
int count = 0;
class sample
{
public:
sample ( )
{ count ++;
cout << “\n No. of object created” << count;
}
5.6 OOPs Programming

~ sample ( )
{
cout << “\n no. of object destroyed “<< count; count - -;
}
};
main ( )
{
cout << “\n Enter main”;
sample S1, S2, S3, S4;
{
cout << “\n Enter block”;
sample S5;
}
{
cout << “\n Enter block 2”;
sample S6;
}
cout << “Re-enter main \n”;
}
ouput:
Enter main
No. of object created 1
No. of object created 2
No. of object created 3
No. of object created 4
Enter block 1
No. of object created 5
Re-enter main
Constructors and Destructors 5.7

No. of object destroyed 4


No. of object destroyed 3
No. of object destroyed 2
No. of object destroyed 1

5.4 CONSTRUCTOR OVERLOADING

A class can have multiple constructors. This is called constructor overloading. All the
constructors have the same name as the corresponding class, and they differ only in terms of
their signature (in terms of the number of arguments, or data types of their arguments or
both).

// Constructor overloading
# include <iostream.h>
class account
{
int accno, balance;
public:
account ( ) // Constructor no. 1
{
cout << “Enter the account no”;
cin >> accno;
cout << “Enter the balance”
cin >> balance;
}
account (int a) // Constructor no. 2
{
accno = a;
balance = 0;
}
account (int acval, int ball) // Constructor no. 3
5.8 OOPs Programming

{
accno = acval;
balance = bal;
}
void display ( )
{
cout << accno << balance;
}
void moneytransfer (account & acc, int amount);
};
Void account :: money transfer (account & acc, int amount)
{
balance = balance-amount;
acc. balance = acc. balance + amount;
}
void main ( )
{
int money;
account acc1; // user Constructor 1
account acc2 (10); // user Constructor 2
account acc3 (20, 40); // user Constructor 3
acc1.display ( );
acc2.display ( );
cout << “How much money is to be transferred from acc3 to acc1”;
cin >> money;
acc3.moneytransfer (acc1, money);
acc1.display ( );
acc2.display ( );
acc3.display ( );
}
Constructors and Destructors 5.9

Output
Enter the accno:2
Enter the balance : 100
7
100
10
0
20
40
Difference between Constructors and Destructors

I Arguments cannot be passed to destructors.

I Only one destructor can be declared for a given class destructors cannot be
overloaded.

I Destructors can be virtual, while constructors cannot be virtual.

I Constructors which do not take arguments explicitly are called default consts.

5.5 CONSTRUCTORS WITH DEFAULT ARGUMENTS

// Constructors with default arguments


# include <iostream.h>
class complex
{
private:
float real, imag;
public:
complex ( ) // Constructor 0
{
real = imag = 0.0;
}
5.10 OOPs Programming

complex (float real-in, float imag-in = 0.0) // Constructor 1


{
real = real-in;
imag = imag-in;
}
void show ( )
{
cout << real << “+;” << imag;
}
complex add (complex C2);
};
complex complex :: add (complex C2)
{
complex temp;
temp.real = real + C2.real;
temp.imag = imag + C2.imag;
return (temp);
}
void main ( )
{
complex C1 (1.5, 2.0); // uses constructor 1
complex C2 (2.5); // uses constructor 1 with default imag value
complex C3;
C1.show ( );
C2.show ( );
C3 = C1.add (C2);
C3.show ( );
}
Constructors and Destructors 5.11

Output
1.5 + j 2
2+j5
3.5 + j 7
If no constructors are defined, the compiler tries to generate a default constructor. This
default constructor simply allocates storage to build an object of its class. A constructor that
has all default arguments is similar to a default (no argument) constructor, because it can be
called without any explicit arguments. This may also lead to errors.
class X void main ( )
int value {
public: X’C; // Error: This leads to errors as
X() // Compiler will not be able to
{ // decide which constructor should
value = 0; // be called
}
X (int i = 0) X C1(4); // OK
{
value = i; }
}

5.6 NAMELESS OBJECTS

C++ not only supports the creation of named objects, but also the creation of unnamed
objects.

Syntax
classname (arguments);

Passing arguments to an object is optional and if no arguments are mentioned, a default


constructor of the class is invoked. If arguments are mentioned in the object creation statement,
C++ invokes a constructor of the class that matches with the argument types. After execution
of the constructor, nameless objects are immediately destroyed and the destructor of the
class is invoked as a part of the object clean-up activity. The scope of a nameless object is
limited only to the statement in which it is created.
5.12 OOPs Programming

The feature of nameless object creation is useful in functions returning an object.


// Nameless object creation
# include <iostream.h>
class nameless
{
int a;
public:
nameless ( )
{
cout << “constructor” << endl;}
~ nameless ( )
{
cout << “destructor” << endl;}
};
void main ( )
{
nameless ( );
nameless n1;
nameless n2;
cout << “Program terminates”;
}
OIP
Constructor ← nameless ( )
Destructor ← nameless ( )
Constructor ← nameless n1 ( )
Constructor ← nameless n2 ( )
Program terminates
Destructor ← nameless n1 ( )
Destructor ← nameless n2 ( )
Constructors and Destructors 5.13

5.7 DYNAMIC INITIALIZATION THROUGH CONSTRUCTORS

Object’s data members can be dynamically initialized during runtime, even after their
creation. One advantage is that it supports different initialization formats using overloaded
constructors. This provides flexibility of using different forms of data at runtime depending
upon the user’s need.
// Object with different name pattern
# include <iostream.h>
# include <string.h>
class name
{
char first [15]; // first name
char middle [15]; // middle name
char last [15]; // last name
public:
name ( ) // constructor 0
{
first [0] = middle [0] = last [0] = ‘\0’;
}
name (char * firstname) // constructor 1
{
strcpy (first, firstname);
middle [0] = last [0] = ‘\0’;
}
name (char * firstname, char * middle name)
{
strcpy (first, firstname);
strcpy (middle, middle name);
last [0] = ‘\0’;
}
5.14 OOPs Programming

name (Char * firstname, char * middlename, char * lastname)


{
strcpy (first, firstname);
strcpy (middle, middlename);
strcpy (last, lastname);
}
void show ( )
{
cout << “firstname” << first << endl;
if (middle [0])
cout << “middlename” << middle << endl;
if (last [0])
cout << “lastname” << last << endl;
}
};
void main ( )
{
name n1, n2, n3; // constructor 0
n1 = name (“Ramu”); // constructor 1
n2 = name (“Somu”, “S”);
n3 = name (“Raj”, “A”, “B”);
n1.Show ( );
n2.Show ( );
n3.Show ( );
};

5.8 COPY CONSTRUCTOR

A copy constructor is used to declare and initialize an object from another object.
sample S2(S1);
Constructors and Destructors 5.15

Would define S2 and at the same time initializing through copy constructor is known as
copy initialization.
This statement S2 = S1 will not invoke the copy constructor. However, S1 and S2 are
objects, this statement is legal and simply assigns the values of S1 to S2, member by member.
This is the task of the overloaded assignment operator (=).
// Copy constructor
# include <iostream.h>
class code
{
int id;
Public:
code ( ) { } // Constructor
code (int a) {id = a;} // constructor
code (code & x) // Copy constructor
{
id = x.id;
}
void display ( ) {cout << id;}
};
main ( )
{
code A(100); // Object A is created & initialized
code B(A); // Copy constructor called
code C = A; // Copy constructor called
code D; // Copy constructor called
D = A; // Copy constructor not called
A.display ( );
B.display ( );
C.display ( );
D.display ( );
}
5.16 OOPs Programming

5.9 DYNAMIC CONSTRUCTORS

The constructors can also be used to allocate memory while creating objects. This will
enable the system to allocate the right amount of memory for each object when the objects
are not of the same size, thus resulting in the saving of memory. Allocation of memory to
objects at the time of their construction is known as dynamic construction of objects.
// Constructors with new
# include <iostream.h>
class vector
{
int * v; // Pointer to vector
int sz; // Size of a vector
public:
vector (int size)
{
sz = size;
v = new int [size];
}
~ vector ( )
{
delete v; // release vector memory
}
void read ( )
{
for (int i = 0; i < sz : i ++)
cin >> v[i];
}
void show_sum ( )
{
int sum = 0;
for (int i = 0; i < sz; i ++)
Constructors and Destructors 5.17

Sum + = v[i];
cout << sum;
}
};
void main ( )
{
int count;
cout << “How many elements are in the vector”;
cin >> count;
vector v1 (Count);
v1.read ( );
v1.show_sum ( );
}

5.10 CONSTRUCTORS FOR TWO DIMENSIONAL ARRAYS

A class can have multidimensional arrays as data members. Their size can be either
statically defined or dynamically varied during runtime.
// matrix addition
# include <iostream.h>
class matrix
{
int maxrow, maxcol;
int * p; // Pointer to 2 dimensional array
public:
matrix ( )
{
maxrow = 0 ; maxcol = 0;
P = NULL;
}
5.18 OOPs Programming

matrix (int row, int col) // constructor


{
maxrow = row;
maxcol = col;
p = new int * [maxrow]; // dynamic allocation
for (int i = 0; <maxrow; i ++)
p[i] = new int maxcol];
}
~ matrix ( )
{
for (int i = 0; i <maxrow; i ++>
delete p[i];
delete p;
}
void add (matrix & a, matrix & b)
{
int i, j;
maxrow = a.max row;
maxcol = a.max col;
for (i = 0; i <maxrow ; i ++>
for (f = 0; j <maxcol ; j ++>
p[i] [j] = a.p[i][j] + b.p[i][j];
}
void read ( )
{
int i, j;
for (i = 0; i <maxrow ; i ++>
for (j = 0; j <maxcol ; j ++>
Constructors and Destructors 5.19

{
cin >> p[i][j];
}
}
void show ( )
{
for (int i = 0; i <maxrow; i ++>
{
cout << endl;
for (int i = 0; j <maxcol; j ++>
cout << p[i][j] << “ ”;
}
}
};
void main ( )
{
int n, m;
cin >> m >> n; // no. of rows & coumns
matrix a(m, n);
a.read ( );
matrix b(m, n);
b.read ( );
matrix c(m, n);
c.add (a, b);
c.show ( );
}

You might also like