Constructor
- Constructor is the special method whose name is same
as the class name which called automatically when objects are
created.
- They are used to initialize an instance variables of
object.When objects are created, its instance variable must gets
some valid value.This is done by the constructor.
Default
constructors
- These are the constructors taking no parameters.
- Programmer can define default constructor without providig
parameters and using these, instance varibles can be initialized
with some default values.
- When the programmer writes no constructor,the compiler itself
provide a default constructor
- The purpose of default constructor is to assign same default
values to all objects which are created by without providing any
values(parameters)
- On contrast, parameterized constructor takes parameters and
initialize instance variables using these parameters.
- The purpose of parameterized constructor is to provide user
wanted specific values to the variables of different objects
Destructor
- Destructors are the method whose name is same as the class name
but preceeded by tilde(~) symbol
- This method called automatically when objects are
destructed
- It is used to de allocating or deleting the resources such as
heap memory,network connections,files after usage
Example
Class sample
{
int *ptr;
ifstram f;
Sample()
{
ptr=new int[50];
f.open("student.txt")
}
~Sample()
{
delete [] ptr;
f.close();
}
}
- In the above example,inside the constructor resources are
acquired and inside the destructor heap memory is deallocated and
file is closed.