New course! Every coder should learn Generative AI!
Try a free lesson+ 1
When an object is created, constructor will be executed automatically. Constructor is usually used to initialize the variables.
The destructor will be executed before the program ends.
For example,
class A {
public:
A() {
//code for constructor}
~A() {
//code for destructor}
}
int main() {
A obj; //create object of class A
//some other codes
return 0;
}
When the program starts, constructor will be called because the object of class A is declared. Just before the program ends, destructor will be called as the object of class A is destroyed.