Destructors in Object Oriented Programming ( OOPS) – C++

In this c++ tutorial, we are going to discuss the destructors which is used to delete an object in classes. Go through this tutorial to learn destructors in C++.

What is Destructors in C++

Destructors are opposite to constructors, constructors initialize an object in a class where destructors are member functions which deletes objects in a class. There can be only one destructor in a class having the same name as class name precedes by ~ ( sign).

Syntax :- ~ class_name ()

Properties of Destructors in C++

  • Destructors have the same name as a class.
  • Destructors name precede by ~ ( sign ) .
  • Destructors do not accept any parameter.
  • Destructors do not have any return type.
  • Only one destructor in a class is allowed.
  • Destructors can be defined privately.

Code snippet how to declare a destructor in a class in C++

  ~codespeedy()
{
    cout<<"object is being deleted"<<endl;
}

Algorithm of destructors in OOP

  • Declare a class with name codespeedy.
  • Take x and y as private data members of integer type.
  • Declare a non-parameterized constructor in public and initialize the value of x and y and show that object is being created.
  • Declare a member function show() have return type void to print the value of x and y.
  • Declare a destructor which shows that the object is being deleted/destroyed.
  • Now, in the main class create an object with the name ‘c’ of class codespeedy.
  • Now, call function void show( ).

C++ code implementation of destructors in class

#include<bits/stdc++.h>
 
using namespace std;
 
  class codespeedy
{
   int x;
   int y;
   
     public :
     
     codespeedy()
    {
        x=10;
        y=20;
        
        cout<<"Object is being created"<<endl;
    }
    
      void show()
    {
        cout<<"value of x is :"<<x<<endl;
        cout<<"value of y is :"<<y<<endl;
    }
    
      ~codespeedy()
    {
        cout<<"object is being deleted"<<endl;
    }
};

  int main()
{
    codespeedy c;
    
     c.show();
}

OUTPUT

Object is being created
value of x is :10
value of y is :20
object is being deleted

Finally, You may also learn,



Leave a Reply

Your email address will not be published. Required fields are marked *