Create Destructors to clean up the mess - C++ Class

C++ examples for Class:Destructor

Introduction

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 {
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;
  }
};
 

Related Tutorials