Every time,
whenever we are making a class, we have to call a function to initialize the
value to the class variables.
That
means, before further use of class or defining functions as per requirement, we
are making an extra function just to initialize the value to the object.
To overcome this problem, Constructor was introduced.
Constructors
A
constructor is a member function of a class with the same name as that of its
class name.
The
constructor is used to initialize the object of that class type with a legal initial
value.
Constructor
automatically gets called when the object is created of that class.
Syntax:
class Class_name{
private:
variable ;
public:
Class_name()
{
/* This is
Constructor */
statement ;
}
};
Destructors
A destructor
is a member function of a class with the same name as that of its class name
but starts with ~ symbol .
The destructor
is used for all clean-up jobs like closing file or releasing memory area
automatically .
Destructor
automatically gets called when the block ( i.e. { } ) of the object end .
Syntax:
class Class_name{
private:
variable
;
public:
Class_name()
{
/* This is
Constructor */
statement ;
}
~Class_name()
{
/* This is Destructor
*/
statement ;
}
};
0 comments:
Post a Comment
Please give your valuable suggestions