+ 1

Why are there deconstructors, in classes?

Like do we only need deconstructors when we have constructors, or always. If so, do we always need to a have a constructor in a class?

14th Dec 2016, 4:18 AM
Ruchi Patil
Ruchi Patil - avatar
7 Answers
+ 2
In C++ a constructor is used for initializing an object. Usually, you would use a constructor to pass arguments into a newly instantiated object, and those arguments would be set to private members of the object. ... A destructor is called after the parent object is removed from scope or when it is deleted from memory. Now answer to your question When declaring a class in C++ you do NOT have to explicitly define a constructor or destructor for your class because they are already implicitly defined.However, a constructor is needed so that when the class is instantiated all the variables and functions exist in memory. This allows you to use the class by name along with all the functions and variables. The destructor is used to clean up memory and release the memory that was used for the class. Some believe that a destructor isn’t needed because garbage collection will take care of it. It can, but it does a bad job of it. So USE the destructor it will help in the end.
14th Dec 2016, 5:02 AM
Vipul Walia
Vipul Walia - avatar
+ 1
It makes more sense now. Thanks!!
14th Dec 2016, 5:36 AM
Ruchi Patil
Ruchi Patil - avatar
+ 1
First, let me give you the definition of Destruction A destructor is a class member function that is executed when an object of that class is destroyed. Whereas constructors are designed to initialize a class, destructors are designed to help clean up. Compiler has default destructor, then why we need a destructor explicitly ? Answer is : a dynamically allocated object is explicitly deleted using the delete keyword, the class destructor is called (if it exists) to do any necessary clean up before the object is removed from memory. #include <iostream> #include <cassert> using namespace std ; class IntArray { private: int *m_array; int m_length; public: IntArray(int length) // constructor { assert(length > 0); m_array = new int[length]; m_length = length; } ~IntArray() // destructor { // Dynamically delete the array we allocated earlier delete[] m_array ; } void setValue(int index, int value) { m_array[index] = value; } int& getValue(int index) { return m_array[index]; } int getLength() { return m_length; } }; int main() { IntArray ar(10); // allocate 10 integers for (int count=0; count < 10; ++count) ar.setValue(count, count+1); std::cout << "The value of element 5 is: " << ar.getValue(5); return 0; } // ar is destroyed here, so the ~IntArray() destructor function is called here
14th Dec 2016, 6:14 AM
Mock
Mock - avatar
0
Just a note on Vipul's answer: He is wrong - C++ does not have a GC at all. So there is no "automatic" freeing of memory allocated by your class on the heap (using 'new') - like what happens in Java and C#. You have to do it explicitly yourself in your destructor. If you neglect to define a destructor, the compiler will automatically generate one, but this "automatically generated" destructor will not free memory you allocated dynamically on the heap. It will, however, call the destructors on "instance" members. Maybe this sounds a bit confusing, so here is an example: class A { public: A(){ax = new int[10];} ~A(){delete []ax} private: int *ax; }; class B { public: B(){a1 = new A;} // ~B(){delete a1;} private: A* a1; A a2; }; If you do not have the B destructor, the compiler will generate a "default" destructor for you, but it will only implicitly call the a2 destructor (since it is an instance member), but not the a1 destructor (since it is dynamically allocated). In this case your program will leak the 10 int array allocated for ax in a1 as well as a1.ax itself (so the leak would be 10 ints + 1 int pointer). For class B you have no choice, you MUST create your own destructor to free a1 explicitly in your own destructor.
14th Dec 2016, 12:59 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
0
Answer to @Ettienne Implicit garbage collection could have been added in, but it just didn't make the cut. Probably due to not just implementation complications, but also due to people not being able to come to a general consensus fast enough. A quote from Bjarne Stroustrup himself: I had hoped that a garbage collector which could be optionally enabled would be part of C++0x, but there were enough technical problems that I have to make do with just a detailed specification of how such a collector integrates with the rest of the language, if provided. As is the case with essentially all C++0x features, an experimental implementation exists. General overview: C++ is very powerful and allows you to do almost anything. For this reason it doesn't automatically push many things onto you that might impact performance. Garbage collection can be easily implemented with smart pointers (objects that wrap pointers with a reference count, which auto delete themselves when the reference count reaches 0). C++ was built with competitors in mind that did not have garbage collection. Efficiency was the main concern that C++ had to fend off criticism from in comparison to C and others. There are 2 types of garbage collection... Explicit garbage collection: C++0x will have garbage collection via pointers created with shared_ptr If you want it you can use it, if you don't want it you aren't forced into using it. You can currently use boost:shared_ptr as well if you don't want to wait for C++0x. Implicit garbage collection: It does not have transparent garbage collection though. It will be a focus point for future C++ specs though.
14th Dec 2016, 1:41 PM
Vipul Walia
Vipul Walia - avatar
0
Answer to Vipul's answer to my earlier post: I was referring to this statement by you: "Some believe that a destructor isn’t needed because garbage collection will take care of it. It can, but it does a bad job of it." You seem to imply there is currently garbage collection in C++ (since you refer to it "doing a bad job" for example). The fact is there are currently no GC in C++ and, yes, i am aware of the efforts by the C++ Standards Commitee to include it at some point. There are some 3rd party GC's available for C++ today (notably the Boehm GC), but that is not standard in any C++ compiler I am aware of. You have to add it yourself into your projects. Also, the use of shared_ptr (from Boost and others) as a memory management solution is not normally seen as "garbage collection" (at least in the way it is implemented in Java/C# i.e. with scanning collectors). In fact, the use of shared_ptr's are normally seen as an _alternative_ to garbage collection in that they are a "reference counting" solution to the same problem. Languages like Apple's Swift, that are based on ARC (automatic reference counting), has build their whole memory management solution on reference counting, and this is seen as a distinct form of memory management different to (what we typically refer to) as "garbage collection". See https://en.wikipedia.org/wiki/Swift_(programming_language)#Memory_management and you will see it refers to ARC, and never to "garbage collection". The advantages/disadvantages of "reference counting" vs "garbage collection" are quite different and distinct from one another, and to present "reference counting" as "garbage collection" will just cause confusion for people. I think one of the main problems here is that people use the term "garbage collection" quite loosely, but they are typically talking about "scanning collectors", like what the JVM and .NET uses.
14th Dec 2016, 3:46 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
0
Thank you so much for clearing my doubt and pardon me if i referred anywhere wrong info.
14th Dec 2016, 3:49 PM
Vipul Walia
Vipul Walia - avatar