Destructors in C++ C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
Destructors in C++
Destructors in C++
Destructor is a member function that destructs or deletes an object.
When is the destructor called?
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
There can only one destructor in a class with class name preceded by ~, no parameters, and no return type.
How destructors are different from a normal member function?
Destructors have the same name as the class preceded by a tilde (~). Destructors don’t take any argument and don’t return anything
Example
#include <iostream> using namespace std; class MyClass{ public: //Constructor MyClass(){ cout<<"Constructor is called"<<endl; } //Destructor ~MyClass(){ cout<<"Destructor is called"<<endl; } //Member function void display(){ cout<<"Hello World!"<<endl; } }; int main(){ //Object created MyClass obj; //Member function called obj.display(); return 0; }
Output:
Constructor is called Hello World! Destructor is called
Destructor rules
1) The name should begin with a tilde sign(~) and must match the class name.
2) There cannot be more than one destructor in a class.
3) Unlike constructors that can have parameters, destructors do not allow any parameter.
4) They do not have any return type, just like constructors.
5) When you do not specify any destructor in a class, the compiler generates a default destructor and inserts it into your code.