FAQ 2.20 What are the basics of adding a destructor to a class?

graphics/new_icon.gif

Every class can optionally have a destructor (a.k.a. dtor). A destructor is a special member function that is automatically called whenever an object of the class is destroyed. This feature of C++ allows the class developer to close any files the object has opened, release any memory the object has allocated, unlock any semaphores the object has locked, and so on. In general, this gives an object a chance to clean up after itself.

Syntactically a destructor is a member function whose name is a tilde character (~) followed by the name of the class. Like constructors, destructors cannot have a return type. Unlike constructors, destructors can, and often are declared with the virtual keyword, and a class can have only one destructor. Like all member functions, a destructor is declared in the class body, which normally appears in the class's header file. For example, the header file for class Car might be file Car.hpp.

 #ifndef CAR_HPP #define CAR_HPP class Car { public:   virtual ~Car();                                    <-- 1   // ... protected:   // ... }; #endif 

(1) Declaration of a destructor

Destructors are often defined in the source file for class Car, such as in file Car.cpp:

 #include "Car.hpp" Car::~Car() {   // ...                                             <-- 1 } 

(1) Clean-up code goes here

If a class doesn't have a destructor, the compiler conceptually gives the class a destructor that does nothing. Therefore if a class doesn't need to do anything special inside its destructor, the easiest thing to do is to not even declare a destructor. In fact, in applications that follow the guidelines of this book, a destructor is needed only in a relatively small percentage of the classes.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net