Explain constructor and destructor and their characteristics
Answers
Answer:
Characteristics of constructor
They should be declared in the public section.
They are invoked automatically when the objects are created.
They do not have return (data type) type not even void and there for they cannot return any values.
They can not be inherited, the a derived class can call the base class constructor.
They make implicit calls to the operator new and delete when memory allocation is required.
Constructors – A constructor is a member function of the class and it is called each time when an object of that class is created. Therefore, an initialization needs to be done when an object is created which automatically done by the constructor function. It is called constructor, because it constructs the value of data members of the class.
Destructors – Destructors are the complement of the constructors. The destructor function has the same as the constructor, but it is preceded by a (tilde sign). The basic purpose of a destructor is to kill the object and to help release the memory accupied by the object. That is
integer ( )
{}
A destructor never takes any argument nor does it return any value. It is called implicitly by the storage that is no longer accessible.
Example –
#include<iostream.h>
Class class_name
{
Int a, b;
Public :
Class_name (int x, int y); //constructor
class_name ( ); // destructor function
Void show ( );
};
Class_name ::class_name (int x, int y)
{
A = x;
B = y;
}
Void class_name :: show ( )
{