C++ Destructors

A Destructor in C++ destructs an object. It has the same name as the class name and gets automatically called when an object gets created like Constructors.

Syntax – Destructors

Let us see the syntax of Destructors with our class name Studyopedia. It is prefixed by a tilde sign as shown below:

Studyopedia() {     // Constructor
   // Code comes here
}

~Studyopedia() {     // Destructor
   // Code comes here
}

As shown above, the Destructor syntax is like the Constructor, except for the prefixed tilde sign. Remember, the following points about Destructors:

  • Define Destructor only once in a class
  • The access specifier concept does not work on Destructors in C++
  • The Destructors cannot have parameters, unlike Constructors.

Example – Destructors

Let us now see an example of Destructors in C++:

#include <iostream>
using namespace std;

class Rectangle {    
  public:   // Access specifier
  
    // Constructor name is the same as the class name
    Rectangle() {     
      cout << "Constructor gets invoked automatically!!";
      cout << "\nA rectangle has 4 sides, 4 corners, and 4 right angles";
    }
    
    // Destructor name is the same as the class name with a prefixed tilde sign
    ~Rectangle() {     
      cout << "\n\nDestructor gets invoked automatically!!";
    }
};

int main() {
  
  /* Constructor and Destructor gets called automatically when we 
  create an object of a class */
  Rectangle rct;   
  
  return 0;
}

Output

Constructor gets invoked automatically!!
A rectangle has 4 sides, 4 corners, and 4 right angles

Destructor gets invoked automatically!!
C++ Classes and Objects
C++ Pointers
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment