Destructors in C++ (With Examples And Explanation)

What is a destructor?

Destructor is an occurrence part work which is summoned naturally at whatever point an article will be obliterated. Which means, a destructor is the last capacity that will be called before an item is obliterated.

The thing is to be noted here, assuming the item is made by utilizing new or the constructor utilizes new to distribute memory which lives in the stack memory or the free store, the destructor should utilize erase to free the memory.

Properties of Destructor:

  • Destructor work is consequently summoned when the articles are annihilated.
  • It can’t be announced static or const.
  • The destructor doesn’t have contentions.
  • It has no return type not void.
  • An object of a class with a Destructor can’t turn into an individual from the association.
  • A destructor ought to be announced in the public part of the class.
  • The developer can’t get to the location of destructor.

When is destructor called?

A destructor work is called naturally when the item leaves scope:

(1) the capacity closes
(2) the program closes
(3) a square containing neighborhood factors closes
(4) an erase administrator is called

How are destructors not quite the same as an ordinary part work?

  • Destructors have same name as the class went before by a tilde (~)
  • Destructors don’t take any contention and don’t bring anything back

Might there be more than one destructor in a class?

No, there can one destructor in a class with classname went before by ~, no boundaries and no bring type back.

class String {
private:
    char* s;
    int size;
public:
    String(char*); // constructor
    ~String(); // destructor
};
String::String(char* c)
{
    size = strlen(c);
    s = new char[size + 1];
    strcpy(s, c);
}
String::~String() { delete[] s; }

When do we have to compose a client characterized destructor?

On the off chance that we don’t compose our own destructor in class, compiler makes a default destructor for us. The default destructor works fine except if we have progressively allotted memory or pointer in class. At the point when a class contains a pointer to memory assigned in class, we ought to compose a destructor to deliver memory before the class occurrence is annihilated. This should be done to keep away from memory spill.

Could a destructor be virtual?

Indeed, truth be told, it is dependably really smart to make destructors virtual in base class when we have a virtual capacity. See virtual destructor for additional subtleties.
You might jump at the chance to take a test on destructors.

Also ReadHow to Install Minecraft on Linux?

Leave a Reply

Your email address will not be published.