Global Static Object
Global static objects are those objects that are declared outside any block. Their scope is the whole program and their lifespan is till the end of the program.
Example:
C++
// C++ program to demonstrate a global static keyword #include <iostream> class Test { public : int a; Test() { a = 10; std::cout << "Constructor is executed\n" ; } ~Test() { std::cout << "Destructor is executed\n" ; } }; static Test obj; int main() { std::cout << "main() starts\n" ; std::cout << obj.a; std::cout << "\nmain() terminates\n" ; return 0; } |
Output:
Constructor is executed main() starts 10 main() terminates Destructor is executed
We can see that the global static object is constructed even before the main function.
Static Objects in C++
Prerequisite: Static Keyword in C++
An object becomes static when a static keyword is used in its declaration. Static objects are initialized only once and live until the program terminates. They are allocated storage in the data segment or BSS segment of the memory.
C++ supports two types of static objects:
- Local Static Objects
- Global Static Objects.
Syntax:
Test t; // Stack based object static Test t1; // Static object
The first statement when executes creates an object on the stack means storage is allocated on the stack. Stack-based objects are also called automatic objects or local objects. The second statement creates a static object in the data segment or BSS segment of the memory.