What is an constructor and destructor? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

What is an constructor and destructor?

please explain me with an example

15th Feb 2017, 4:39 PM
Akshayarekha
Akshayarekha - avatar
3 Answers
+ 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.
15th Feb 2017, 6:01 PM
POJO
POJO - avatar
+ 1
thanks for the answers
16th Feb 2017, 2:52 PM
Akshayarekha
Akshayarekha - avatar
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
15th Feb 2017, 5:46 PM
RANJIT 07