Destructor functionsThe destructor function is a special function that a class uses to recover the space allocated to an instance of that class. The destructor is called whenever an object goes out of scope. Every class has a destructor function even if none is defined. In this case the equivalent definition is
~X() {}
Where X is the name of the class. Note there is no return type (just like the constructor functions), there are no parameters and the tilde (~) must be present. Destructors should be public to be of any use. There can only be one destructor for a class, but its body can be defined in any chosen fashion. Typically the destructor can use delete on pointers initialized with new to ensure that dangling pointers are not left.
For example, in the class below, the constructor creates a data member with new, and the destructor destroys it.
class Y { ... };
class X {private: Y* mem1;public: X() { mem1 = new Y; } ~X() { delete mem1; }};
Wednesday, July 8, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment