×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

Destructors in C++

Learn: What are the destructors in C++ programming language? How they declared, defined and accessed in a C++ program?

As we have discussed that a constructor is a special type of member function, which calls automatically when object is going to create.

What is Destructor in C++?

A destructor is a special type of member function, which called automatically when scope of an object is going to out i.e. when an object is going to be destroyed.

Properties of a destructor

There are following properties of a destructor:

  • Destructor of a class has the same name as the class name.
  • It does not have a return type.
  • It does not have any argument.
  • It is preceded with the tilde character (~).
  • It cannot be overloaded.

Example of C++ Destructor

Consider the example:

#include <iostream>
using namespace std;

class Demo {
 private:
  int X;

 public:
  // constructor
  Demo(int x) {
    X = x;
    Print();
  }
  // destructor
  ~Demo() {
    cout << "\nDestructor Called";
    Print();
  }

  void Print() { cout << "\nValue of X: " << X; }
};

int main() {
  Demo OB1(10);
  Demo OB2(20);
  Demo OB3(30);

  return 0;
}

Output

Value of X: 10
Value of X: 20
Value of X: 30
Destructor Called
Value of X: 30
Destructor Called
Value of X: 20
Destructor Called
Value of X: 10

NOTE: Constructors are called in order of object declaration, and the destructors are called in the reverse order of its declaration.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.