COMPUTER SCIENCE CONSTRUCTORS AND DESTRUCTORS

DELHI 2002:

2.c) Write the output of the following program.

4

Ans:

#include<iostream.h>
class Counter
{ private:
unsigned int count;
public:
Counter()
{ count=0;}
void inc_Count()
{ count++;
}
int get_Count()
{ return count;
}
};
void main()
{ Counter C1,C2;
cout<<"\nC1="<<C1.get_Count();
cout<<"\nC2="<<C2.get_Count();
C1.inc_Count();
C2.inc_Count();
C2.inc_Count();
cout<<"\nC1="<<C1.get_Count();
cout<<"\nC2="<<C2.get_Count();
}

DELHI 2000:

2.a) Why is destructor function required in classes? Illustrate with the function with an example.

Ans: A destructor is a function which deallocates/frees the memory which was reserved by the constructor.

Eg:
class Sample
{
Int i,j;
Public:
Sample(int a, int b)
//Constructor
{ i=a; j=b; }
~Sample()
{ cout<<”Destructor at work\n”; }
------
};
void main( )
{
Sample s1(3,4); //Local object s1
constructed with values 3 // and 4 using Sample ( )
-----
------
----//Automatically s1 is destructed at the end of the block
//using destructor ~Sample( )
}

Here in the above example the destructor
~Sample( ) will be automatically executed at the time of destruction of an object, and which is used to de-allocate the memory, before doing it whatever written in the destructor will be executed.

Ie in the above example whenever an object of the class is being destroyed, “Destructor at work” will be displayed.

 

CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( mrkdata@yahoo.com )


Warning: include_once(../../ebooks-footer19.php): Failed to open stream: No such file or directory in /home/cbseguess/public_html/ebooks/xii/coumputer-science/constructors_destructors9.php on line 138

Warning: include_once(): Failed opening '../../ebooks-footer19.php' for inclusion (include_path='.:/opt/cpanel/ea-php83/root/usr/share/pear') in /home/cbseguess/public_html/ebooks/xii/coumputer-science/constructors_destructors9.php on line 138

Warning: include_once(../../../footer19.php): Failed to open stream: No such file or directory in /home/cbseguess/public_html/ebooks/xii/coumputer-science/constructors_destructors9.php on line 140

Warning: include_once(): Failed opening '../../../footer19.php' for inclusion (include_path='.:/opt/cpanel/ea-php83/root/usr/share/pear') in /home/cbseguess/public_html/ebooks/xii/coumputer-science/constructors_destructors9.php on line 140