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
Destructors are often defined in the source file for class Car, such as in file Car.cpp: #include "Car.hpp" Car::~Car() { // ... <-- 1 }
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. |