When are static objects destroyed in C++?

C++ProgrammingServer Side Programming

Static objects are declared with the keyword static. They are initialized only once and stored in the static storage area. The static objects are only destroyed when the program terminates i.e. they live until program termination.

A program that demonstrates static objects in C++ is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class Base {
   public :
   int func() {
      int a = 20;
      cout << "The value of a : " << a;
   }
};
int main() {
   static Base b;
   b.func();
   return 0;
}

Output

The output of the above program is as follows.

The value of a : 20

Now let us understand the above program.

The function func() in class Base declares an int variable a and then displays the value of a. The code snippet that shows this is as follows.

class Base {
   public :
   int func() {
      int a = 20;
      cout << "The value of a : " << a;
   }
};

In the function main(), a static object b is created of class Base. Then function func() is called. Since object b is static, it is only destroyed when the program terminates. The code snippet that shows this is as follows.

int main() {
   static Base b;
   b.func();
   return 0;
}
raja
Published on 22-Nov-2018 08:01:53
Advertisements