Tuesday, July 28, 2009

Does the destructor in C++ have a definition ?

In C++ constructors have definitions that we write in the .cpp implementation file. Once in the lab I had an error in my program, my lab teacher told me that this was because I defined a destructor in my class but didnt write its definition. According to what I read in the book and what my lecturer told us, you define a destructor in you class using (~) followed by the class name and () no parameters, and that it executes automatically when the object goes out of its scope (class/object link with memorey breaks). Moreover, the destructor wasnt used alot in the book and we didnt use it much in the lectures so I dont know what the answer is. Does it have a definition ? and if it does then what would it be ?

Does the destructor in C++ have a definition ?
class C {


~C() {


// write your code here


}


}


And yes destructor has to be defined.
Reply:Destructors should free up any dynamically allocated memory your class uses (declared with the "new" operator or malloc()). Also, classes which will be inherited from should have virtual destructors so their subclasses can also free up their memory when instances are destroyed.


No comments:

Post a Comment