+ 3
Why are constructors and deconstructors so essential for you personally in C++?
A few days ago I watched an interview between the creator of C++ and Lex Fridman who teaches at MIT asking Bjarne Stroustrup what his personally nicest and cleanest feature of C++ is and he answered constructors and deconconstructors. Now to my question above. Why do you think these two are so crucial when it comes to writing code in cpp? What do you personally think is the great idea behind constructors and deconstructors? Here the interview --> https://www.youtube.com/watch?v=uTxRF5ag27A
4 Answers
+ 6
Max, whenever you want to do something, first of all you have to create it, this is what a constructor do and after finishing the work, It's your duty to clean it up also so that you can create something else there, this cleaning process is what destructors do
That's why constructor and ~destructors is cleanest one
+ 6
I don't know if I should say nicest or cleanest, but as I see it, constructor allows an easy way to setup a newly created object.
Without constructors we would have to instantiate the object first, then call some setter member function to assign a desired value for member data. I just find that be less practical that's all.
+ 2
Thanks for the answers.
I mean I was well aware what they do but it didn't occure to me that it's so crucial for memory management. My first language was python and there you just type the code you want to execute and all is done. This hierarchy with heap, stack, ... was new to me.
+ 2
It probably makes sense to see this as 'improvements in regards to C'.
The whole procedure of requiring and releasing heap memory and pointing around within it easily can lead to a lot of errors.
By having a mechanism that automatically calls the creative and destructive part of an object, so that you can be sure they'll automatically happen, you can put the heap operations into the class definitions, so that they become easier to oversee and control.
This way, when you use the class later creating instances, it looks like no heap operations are necessary - it's all done for you because you encapsulated it in the class.
And you can see Python as a kind of mech suit in which you sit and that's doing ALL of that stuff for you in the background.
It's convenient, but it's also a huge robot, and you have little control over what exactly happens within the machine.