Destructors in C++

Destructors

Destructors in C++ are opposite of constructors while constructors initialize the value for an object that is instantiated. Destructors destroy the objects and assigned value to them.

Destructors in C++

Destructors in C++ are called when –

  • The object goes out of scope of execution
  • Are automatically called by compiler if are not manually defined by the user

Destructors are special functions of a class

  • Have the same name as the name of the class
  • Are preceded with~ for example for class named as Demo the destructor will be ~Demo()
  • No argument passing or copying happens unlike constructors where we can parameterize or copy

Syntax

class Demo
{
public:
~Demo();
};

Example of a Destructor

Run
#include <iostream>
using namespace std;
class Demo
{
  public:
  //Initialising the Constructor Destructor
  Demo()
  {
    cout << "Object has been Constructed\n";
  }
  ~Demo()
  {
   cout << "We have Destroyed the object\n";
  }
};
int main()
{
  Demo demo; 
  // Constructor Called
  int temp=1;
  if(temp)
  {
    // Constructor calling happens here
    Demo prepinsta; 
  } 
  // The scope of the object initialised prepinsta has ended here so the destructor will be called automatically by the system.
} 
// Destructor called for Demo as demo object's out of scope

Output –

Object has been Constructed
Object has been Constructed
We have Destroyed the object
We have Destroyed the object

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription