Constructor Overloading: The constructor of a class may also be overloaded so that even with different number and types of initial values, an object may still be initialized.
Default Arguments Versus Overloading: Using default arguments gives the appearance of overloading, because the function may be called with an optional number of arguments.
Eg: Prototype
Special Chracteristics of Constructors:float amount (float principal, int time=2, float rate=0.08);
Can be called as Amount(2000.0,4,0.10);
Amount(3520.5,3);
Amount(5500.0);
Eg: Sample obj1=Sample(13,22.42);
Destructor:A destructor is used to destroy the objects that have been created by a constructor. A destructor destroys the values of the object being destroyed. A destructor is also a member function whose name is the same as the class name
but is preceded by tilde(~). A destructor takes no arguments, and no return types can be specified for it (not even void). It is automatically called by the compiler when an object is destroyed. A local object, local to a block, is destroyed when the block gets over; a global or static object is destroyed when the program terminates. A destructor cleans up the storage (memory area of the object) that is no longer accessible.
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
// & 4 using Sample ( )
-----
----/*Automatically s1 is destructed at the end of the block using destructor ~Sample( )*/
}
Need for Destructors: During construction of any object by the constructor, resources may be allocated for use. (for example, a constructor may7 have opened a file and a memory area may be allotted to it). These allocated resources must be de allocated before the object is destroyed.A destructor performs these types of tasks.
Some Characteristics of Destructors:
CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )