CBSE Computer Science - Revision Tour(Solved)

CBSE Guess > eBooks > Class XII > CBSE Computer Science Constructors And Destructors Solved Revision Tour By Mr. Ravi Kiran

COMPUTER SCIENCE CONSTRUCTORS AND DESTRUCTORS

Previous Index Next

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.

 

Previous Index Next

CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )