When an object is destroyed, its destructor is called.
A class can have only one destructor.
The compiler provides a default version of the destructor that does nothing if you don't define one.
The definition of the default constructor looks like this:
~ClassName() {}
The destructor cannot have parameters or a return type.
The default destructor in the Pool class is:
~Pool() {}
If the definition is placed outside the class, the name of the destructor would be prefixed with the class name:
Pool::~Pool() {}
#include <iostream> #include <memory> class Pool {/*from w ww . ja v a 2 s . c o m*/ private: double length {1.0}; double width {1.0}; double height {1.0}; static int objectCount; // Count of objects in existence public: // Constructors Pool(double lv, double wv, double hv); Pool(double side) : Pool {side, side, side} // Constructor for a cube { std::cout << "Pool constructor 2 called." << std::endl; } Pool() // No-arg constructor { ++objectCount; std::cout << "No-arg Pool constructor called." << std::endl; } Pool(const Pool& pool) // Copy constructor : length {pool.length}, width {pool.width}, height {pool.height} { ++objectCount; std::cout << "Pool copy constructor called." << std::endl; } double volume() const; // Function to calculate the volume of a pool static int getObjectCount() { return objectCount; } ~Pool() // Destructor { std::cout << "Pool destructor called." << std::endl; --objectCount; } }; int main() { std::cout << "There are now" << Pool::getObjectCount() << "objects." << std::endl; const Pool pool1 {2.0, 3.0, 4.0}; // An arbitrary pool Pool pool2 {5.0}; // A pool that is a cube std::cout << "There are now" << Pool::getObjectCount() << "objects." << std::endl; for (double d {} ; d < 3.0 ; ++d) { Pool pool {d, d + 1.0, d + 2.0}; std::cout << "Pool volume is" << pool.volume() << std::endl; } std::cout << "There are now" << Pool::getObjectCount() << "objects." << std::endl; auto pPool = std::make_shared<Pool>(1.5, 2.5, 3.5); std::cout << "Pool volume is" << pPool->volume() << std::endl; std::cout << "There are now" << pPool->getObjectCount() << "objects." << std::endl; }