C++ Destructors in OOP | Rules & Properties of Destructor in OOP

C++ Destructors in OOP | Destructor rules in OOP | Properties of Destructor| OOP Tutorial in C++

In this tutorial, we are going to learn about the C++  Destructor in OOP, Destructor in C++, When is destructor called? ,Destructor rules in OOP, Properties of Destructor in OOP

C++ Destructor in OOP :

Destructor is a special class function which destroys the object as soon as the scope of object ends. A destructor works opposite to constructor; it destructs the objects of classes.

The syntax for destructor is same as that for the constructor, the class name is used for the name of destructor, with a tilde ~ sign as prefix to it.

Note: C++ destructor cannot have parameters. Moreover, modifiers can't be applied on destructors.

Syntax of Destructor in C++ :        

class A {


    ~A() // defining destructor for class


        // statement



Example of Destructor in C++ :

 #include <iostream>  
 using namespace std;  
 class CodeShikhi  
             cout<<"Constructor Invoked"<<endl;    



             cout<<"Destructor Invoked"<<endl;    



 int main()   


     CodeShikhi oop1; //creating an object of CodeShikhi   

     CodeShikhi oop2; //creating an object of CodeShikhi  

     return 0;  



Constructor Invoked

Constructor Invoked

Destructor Invoked

Destructor Invoked

When does the destructor get called?

A destructor is automatically called when:

(1) the function ends 

(2) the program ends 

(3) When a scope (the { } parenthesis) containing local variable ends.

(4) When you call the delete operator.

C++ Destructor Rules in OOP:

1) Name should begin with tilde sign(~) and must match 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, compiler generates a default destructor and inserts it into your code. 

What are the Properties of Destructor in OOP?

  1. Destructor function is automatically invoked when the objects are destroyed.
  2. It cannot be declared static or const.
  3. The destructor does not have arguments.
  4. It has no return type not even void.
  5. An object of a class with a Destructor cannot become a member of the union.
  6. A destructor should be declared in the public section of the class.
  7. The programmer cannot access the address of destructor.


Next Post: C++ Array of Objects in OOP | Array of Objects with Example in C++| OOP Tutorial in C++

0 Response to C++ Destructors in OOP | Rules & Properties of Destructor in OOP

Post a Comment