1. What is destructor?
Ans. Destructor is a member function which is called when an object is deleted/destroyed or goes out of scope.
2. What is the purpose of using a destructor in C++?
Ans. The main purpose of destructor is to free all the resources (opened files, opened sockets, database connections, resource locks etc.) which are allocated during your object’s life time.
3. What is the use of a constructor?
Constructor is a special function having same name as class name. Constructor is called at the time of creating object to your class. Constructor is used to initialize the instance variables of an object while creating it. Constructor is also used to create virtual tables for virtual functions.
4. What if I don’t use copy constructor? Where does it create problem?
Please see copy constructor
5. Does C++ compiler create default constructor when we write our own?
In C++, compiler by default creates default constructor for every class. But, if we define our own constructor, compiler doesn’t create the default constructor.
6. What is the order of constructor execution in C++?
Ans. First base class constructor is executed and then derived class constructor, so execution happens from top to bottom in inheritance tree.
7. What is the order of destructor execution in C++?
Ans. Generally derived class destructor, and then base class destructor. Except in case if we are taking a derived class object into a baseclass pointer (or reference variable), and we forget to give virtual keyword for base class destructor. See virtual destructor for details.
8. Can we have virtual destructors? If so what is the use of virtual destructors.
Ans. Yes, we can. This is to make sure that the correct class destructor is called at run time. Specifically when we use base class pointer or reference to hold the derived class object. If we don’t have virtual destructor, then it will end up in calling only base class destructor.