Professional Documents
Culture Documents
AND
DESTRUCTORS
Harinder Singh
Sukhpal Singh
Thapar University, Patiala
Batch: 2011-2013
ssgilltupatiala
WHAT IS A CONSTRUCTOR ?
In c++ , a constructor is a special member
function whose task is to initialize the objects
of its class.
It is special because its name is the same as
the class name.
It is called constructor because it constructs
the value of data members of the class.
The constructor is invoked whenever an object
of its associated class is created.
ssgilltupatiala
// constructor declared
// constructor defined
ssgilltupatiala
ssgilltupatiala
PARAMETERIZED CONSTRUCTOR
ssgilltupatiala
ssgilltupatiala
EXPLICIT/IMPLICIT CALL
int main()
{
integer int1(0, 100);
integer int2 = integer(25, 75);
cout<<object 1:
int1.function1();
cout<<object 2:
int2.function1();
return 0;
}
Output
object1:
object2:
//implicit call
//explicit call
ssgilltupatiala
//default constructor
//parameterized constructor
//copy constructor
ssgilltupatiala
ssgilltupatiala
ssgilltupatiala
COPY CONSTRUCTOR
It is used to declare and initialize an object
from another object.
e.g
code() { }
code( int a) {id = a;}
code( code &x){ id = x.id; } //copy constructor.
And various calls for them are:
code A(100); // object A is Created and initialized.
code B(A);
// copy constructor called.
code C = A; // copy constructor called again.
code D;
// object D is created , not initialized
D=A;
// copy constructor is not called.
ssgilltupatiala
DYNAMIC CONSTRUCTORS
ssgilltupatiala
DYNAMIC CONSTRUCTORS
class String
{
char *name;
int length;
public:
String ()
{ length = 0;
name = new char[length+1];
}
String (char *s)
{ length = strlen(s);
name = new char[length+1];
strcpy(name, s);
}
};
main()
{
Char *first = ME_SE_CR ;
String name1( first);
String name2( Rupinder);
.
.
.
}
ssgilltupatiala
DESTRUCTORS
~ integer() { }
As new is used to allocate memory in
dynamic constructors, here we use delete to
free that memory.
Never take any argument nor does it return any
value.
It will be invoked implicitly by compiler upon
exit from program or a block or a function.
ssgilltupatiala
DESTRUCTORS
Int count = 0;
class test1
{
public :
~test1()
{
count ++;
cout <<\n no. of object created
<< count ;
}
~test1 ()
{ cout <<\n no. of object destroyed
<< count ;
Count - - ;
}
};
main()
{
cout << \n Enter Main \n;
test1 t1, t2, t3, t4;
{
cout <<\n Entered in block1 ;
test1 t5;
}
{
cout <<\n Entered in block2 ;
test1 t6;
}
cout << \n Re-Enter Main \n;
return 0;
}
ssgilltupatiala
OUT PUT
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
No. of object destroyed 5
Enter block 2
No. of object created 5
No. of object destroyed 5
Re - Enter Main
No. of object destroyed 4
No. of object destroyed 3
No. of object destroyed 2
No. of object destroyed 1
ssgilltupatiala
THANK YOU