Professional Documents
Culture Documents
CHAPTER 5
5.1 CONSTRUCTORS
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
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.
{
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
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 Only one destructor can be declared for a given class destructors cannot be
overloaded.
I Constructors which do not take arguments explicitly are called default consts.
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; }
}
C++ not only supports the creation of named objects, but also the creation of unnamed
objects.
Syntax
classname (arguments);
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
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
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 ( );
}
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
{
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 ( );
}