in this post, you will learn about the destructor in c++ programming and learn why we need to use destructor in programming and how to declare destructor in programming.
syntax: class <class-name> // define a class
{
public:
~<class-name>() // define a destructor
{
code for execution;
}
};
Exmaple:
class test
{
public:
~test()
{
code for exectution;
}
};
Note: always remember one thing about that destructor is always self-called by the compiler at the end of the program. we don't need to call the destructor.
class test
{
static int a;
public:
test()
{
a++;
std::cout<<"\n"<<a<<"object created";
}
~test()
{
std::cout<<"\n"<<a<<"object destroyed";
a--;
}
};
int main()
{
std::cout<<"\n compiler in main block:";
test t1;
std::cout<<"\ncompiler in test class:";
test t2,t3;
std::cout<<"\nExit from test class:";
std::cout<<"\nExit from main block:";
return 0;
}
"Please share this knowledge as much possible as you can and also comment me your queries and questions related to this topic. I will really grateful to help you."
![]() |
learn c++ programming |
Destructor:
A destructor is used to free the memory which is reserved by the constructor.All the rules are the same for the destructor which is applicable for the constructor.
- destructor has no return type.
- we can't pass the arguments in the destructor.
- we used [~] tild sign to when declaring the destructor.
- it also has the same name as the class name.
- it's automatically called by the compilers at the end of the program.
- we can only use the one destructor in one class.
- it's always declared in public scope.
syntax: class <class-name> // define a class
{
public:
~<class-name>() // define a destructor
{
code for execution;
}
};
Exmaple:
class test
{
public:
~test()
{
code for exectution;
}
};
Note: always remember one thing about that destructor is always self-called by the compiler at the end of the program. we don't need to call the destructor.
Example program using destructor:
#include<iostream>class test
{
static int a;
public:
test()
{
a++;
std::cout<<"\n"<<a<<"object created";
}
~test()
{
std::cout<<"\n"<<a<<"object destroyed";
a--;
}
};
int main()
{
std::cout<<"\n compiler in main block:";
test t1;
std::cout<<"\ncompiler in test class:";
test t2,t3;
std::cout<<"\nExit from test class:";
std::cout<<"\nExit from main block:";
return 0;
}
"Please share this knowledge as much possible as you can and also comment me your queries and questions related to this topic. I will really grateful to help you."
0 comments: