OOP

Destructor

A destructor is another special member function in object-oriented programming, similar to a constructor but for the opposite purpose. It’s called automatically when an object is no longer needed and is about to be destroyed.

Here’s why destructors are important:

Even though some programming languages might provide a default destructor, it’s generally good practice to define your own destructor whenever your class manages resources or needs specific cleanup actions. This ensures proper memory management and avoids potential issues in your program.

class Distance {
 private:
  int feet;
  float inches;

 public:
  // Constructor to initialize the distance object
  Distance(int ft, float in) {
    feet = ft;
    inches = in;
  }

  // Destructor to print a message when the object is destroyed
  ~Distance() {
    std::cout << "Distance object destroyed: " << feet << "ft " << inches << "in\n";
  }
};

In this example:

Note:

Practice