What is destructor and its function? Explain with example.


Q.) What is destructor and its function? Explain with example.

Subject: Object Oriented Programming and Methodology

Destructor

In C++, a destructor is a special member function that is called automatically when an object is destroyed. It is declared in the same way as a constructor, but with a tilde (~) prefix.

The destructor's job is to release any resources that were allocated by the constructor. For example, if the constructor allocated memory, the destructor should free that memory. If the constructor opened a file, the destructor should close that file.

Destructors are important because they help to ensure that resources are properly cleaned up when an object is destroyed. This can prevent memory leaks and other problems.

Function of Destructor

The function of a destructor is to:

  • Release any resources that were allocated by the constructor.
  • Reset the object's data members to their default values.
  • Call the destructors of any member objects.

Example

The following is an example of a class with a destructor:

class MyClass {
public:
  MyClass() {
    // Allocate memory and other resources
  }

  ~MyClass() {
    // Release memory and other resources
  }

  // Other member functions
};

When an object of type MyClass is destroyed, the destructor will be called automatically. The destructor will release any memory and other resources that were allocated by the constructor.

Points to Remember

  • Destructors are called automatically when an object is destroyed.
  • Destructors should release any resources that were allocated by the constructor.
  • Destructors should reset the object's data members to their default values.
  • Destructors should call the destructors of any member objects.
  • Destructors can be overloaded.
  • Destructors can be virtual.