×

C++ Static

What is the Static keyword?

In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once during the program's lifetime. And they're valid throughout the duration of the program. The following are examples of static keyword:

  • Static variable in functions
  • Static Class Objects
  • Static member Variable in class
  • Static Methods in class

Static Variables inside Functions:

Throughout the code, the static variable has a particular lifetime.

Even if the function is invoked numerous times, memory for the static variable is only allocated once, and the preceding call's value is carried over to the next function call.

They are not saved in the stack, but rather in the static storage area.

Example:

#include <iostream> 
using namespace std; 
  
void myFunc() 
{  
    // static var initialized in first func call
    static int i = 0; 
    
    cout << i << " "; 
      
    // value is retained from previous func call which will be carried to the upcoming func calls
    i++; 
} 
  
int main() 
{ 
    for (int a = 0; a <= 7; a++)     
        myFunc();
        
    return 0; 
}

Output:

0 1 2 3 4 5 6 7

Explanation:

A function named myFunc() was defined and in that a variable i is defined as static with static keyword which will get printed every time myFunc() will be called. The value is retained in this var i from previous function call which will be carried to the upcoming function call. Then in the main() function myFunc() was called 7 times in loop, so we got our output.

Static Class Objects:

The static keyword applies to class objects as well. Static objects are given storage in the static storage region and have scope until the conclusion of the programme.

Static objects, like other objects, are initialised using constructors. Only primitive datatypes are assigned to zero when the static keyword is used, not user-defined datatypes.

Example:

class Xyz
{
    int a;
    public:
    Xyz()
    {
        a=0;
        cout << "constructor";
    }
    ~Xyz()
    {
        cout << "destructor";
    }
};


void func()
{
    static Xyz obj1;
}


int main()
{
    int n=0;
    if(n==0)
    {
        func();
    }
    cout << "THE END";
}

Output:

constructor 
THE END 
destructor

Explanation:

The class Xyz was defined with variable a and then its constructor Xyz() and destructor ~Xyz() were declared in public. When the object obj1 was declared in the void func(), it was made static using the static keyword. So in the main() function when the given condition was satisfied it printed “THE END” and the destructor was invoked after that. The reason why the destructor wasn't invoked at the conclusion of the if condition, when the reference to object obj1 was removed is that the object was static and had scope until the end of the program, the destructor for this object was executed when the main() function ended.

Static Data Member in Class:

Class members with static data are those that are used by all objects. Other than non-static data members, static data members have a single piece of memory and are not available as a distinct copy with each object.

Since static member variables are not reliant on object initialization, they are not initialised using the constructor.

It must also be manually initialised outside the class. Linker will throw an error if it is not initialised.

Example:

class Xyz
{
    public:
    static int x;
    Xyz()
    {
        // construtor
    };
};


int Xyz::x=10;


int main()
{
    Xyz obj1;
    cout << obj1.x;   // value of x printed
}

Output:

10

Explanation:

In this example, the static variable x is defined inside the class Xyz. The value it had did not changed and was printed with the help of object obj1 in the main() function.

The user cannot change the definition of a static data member once it has been created. It can, however, do mathematical operations.

Static Member Functions:

These methods apply to the entire class, not just a single object.

It may be accessed by utilising an object and the. operator for direct member access. Using the class name and scope resolution :: operator, however, it is more common to invoke a static member function by itself.

Example:

#include <iostream>
using namespace std;


class demoClass
{
  public:
    // static members
    static int x,y;


    // non static member
    int z;


    // static func defined
    // will work only with static members
    static void sum()
    {
        // static function can only access static data members
        cout << "Enter x and y values: ";
        cin >> x >> y;
        cout << "x + y = " << x + y;


        // error:cannot access non static member 'z' in static function ,will show up
        // cin >> z;
    }
};


// both values will again be 0 by default
int demoClass::x;
int demoClass::y;


int main()
{
  // calling static function without object using resolution operator
  demoClass::sum();
  
  return 0;
}

Output:

Enter x and y values: 5 40
x + y = 45

Explanation:

In the class demoClass, static data member x and y were defined and non-static member z was defined. The static function defined will only work with static members. In the function sum() the static function can only access x and y to get the function performed. So in the main() function the static function is called without the object using resolution operator to provide us the output required.

Just static data members & static member functions are accessible to these functions. It is unable to reach regular members since it lacks the "this" keyword.


Related Topics

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

C++ User Defined Exceptions

Overriding and inheriting exception class capabilities may be used to define the new exception. Exception handling can also be used with classes. We may also make an exception for user-defined...

4 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Principles of Object-Oriented Programming in C++

What is Object-Oriented Programming? Object-oriented programming is about creating obejcts that represent the real-world entity . In object-oriented programming, objects are created for the class. One of the main objectives of...

5 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

C++ Keywords

In this article, we will discuss keywords in C++ with their several features and functions. What are Keywords in C++? In C++, a keyword is a reserved word that has a predefined...

4 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

C++ Encapsulation

The following two essential components are present in all C++ programmes: Functions are the parts of a programme that perform actions, and they are termed programme statements (code).Program data is the...

4 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.