Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++
  • C++ Classes and Objects
  • C++ Polymorphism
  • C++ Inheritance
  • C++ Abstraction
  • C++ Encapsulation
  • C++ OOPs Interview Questions
  • C++ OOPs MCQ
  • C++ Interview Questions
  • C++ Function Overloading
  • C++ Programs
  • C++ Preprocessor
  • C++ Templates
Open In App
Next Article:
Static Objects in C++
Next article icon

Static Objects in C++

Last Updated : 14 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  1. Local Static Objects
  2. 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.

Local Static Object

Local static objects in C++ are those static objects that are declared inside a block. Even though their lifespan is till the termination of the program, their scope is limited to the block in which they are declared.

Example:

C++
// C++ program to demonstrate the //  usage of static keyword #include <iostream> class Test { public:     Test() { std::cout << "Constructor is executed\n"; }     ~Test() { std::cout << "Destructor is executed\n"; } };  void myfunc() {   // local static object declaration     static Test obj; }  int main() {     std::cout << "main() starts\n";     myfunc(); // calling function with static object     std::cout << "main() terminates\n";     return 0; } 

Output
main() starts  Constructor is executed  main() terminates  Destructor is executed

If we observe the output of this program closely, we can see that the destructor for the local object named obj is not called after it goes out of scope because the local object obj is static with its lifetime till the end of the program. That is why its destructor will be called when main() terminates.

Now, what happens when we remove static in the above program?As an experiment if we remove the static keyword from the global function myfunc(), we get the output shown below:

main() starts  Constructor is called  Destructor is called  main() terminates

This is because the object obj is now a stack-based object and it is destroyed when it goes out of scope and its destructor will be called.

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.

When are static objects destroyed?

As seen in both examples, static objects are always destroyed at the end of the program whether their scope is local or global. This property allows them to retain their value between multiple function calls and we can even use a pointer to them to access them out of scope.


Next Article
Static Objects in C++

K

kartik
Improve
Article Tags :
  • C++
  • cpp-class
  • cpp-storage-classes
  • cpp-constructor
  • C++-Static Keyword
  • Static Keyword
Practice Tags :
  • CPP

Similar Reads

    Static Keyword in C++
    The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses.In C++, a static keyword can be used in the following context:Table of ContentStatic Variables in a FunctionStatic Member Variab
    5 min read
    C++ Static Data Members
    Static data members are class members that are declared using static keywords. A static member has certain special characteristics which are as follows:Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
    5 min read
    static_cast in C++
    A Cast operator is a unary operator which forces one data type to be converted into another data type.C++ supports 4 types of casting:Static CastDynamic CastConst CastReinterpret CastThis article focuses on discussing the static_cast in detail.Static CastThis is the simplest type of cast that can be
    5 min read
    Static Member Function in C++
    The static keyword is used with a variable to make the memory of the variable static once a static variable is declared its memory can't be changed. To know more about static keywords refer to the article static Keyword in C++. Static Member in C++ Static members of a class are not associated with t
    4 min read
    Project Idea | (Static Code Checker for C++)
    The biggest problem that students face when they join big corporates is difficulty in writing high quality code that these corporates demand. The prime reason for this difficulty is because their minds have been trained in college to just make things work somehow, even if it means using dirty hacks.
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences