- 1
What is an constructor and destructor?
please explain me with an example
3 ответов
+ 1
A constructor is a special
member fn.
It has the same name as of the
class and no return type
specification.
It cannot be explicitly called,
it will be auto executed by
the system when object of the
class is created.
If we donot define any constructor
then system will auto define
a public parameterless constructor
with empty defn.
It is not good to rely on system
generated constructor as it
wont initialize the object to
any valid data.
example:-
class Mario
{
int life;
public:
//default constructor
Mario()
{
life = 3;
}
//parameterized constructor
Mario(int x)
{
life = x;
}
//destructor
~Mario()
{
//read the explanation below
}
};
void main()
{
Mario mobj1 = new Mario();
Mario mobj2 = new Mario(5);
}
mobj1 will be initialized with life 3 which is set rss default in the constructor
mobj2 will be initialized with life 5 which is set by passing parameter to the constructor
____________________________________
A destructor is a special
member function
It is used to clear the
resources (memory, files,
connections, etc) used by
an object.
It is special because
1) It has the same name as
of the class, preceeded by a
~ sign and has not return type
specification.
2) It cannot be called explicitly.
It is auto invoked by the system
when life of an object gets over.
Hence we can say that code of
destructor is the last processing
on the object.
3) It cannot have parameters,
hence it can never be overloaded.
Generally speaking a destructor
reverses the allocations done
by the constructor.
+ 1
thanks for the answers
0
constructor is special function whose name is same as class which initilize to kits object and constructor automatic call when object is created and destructor destroy that object memory allocation when it gets out of scope