×

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

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 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.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

Returning a Function Pointer from a Function in C/C++

Pointers to functions can be used in the C programming language just like standard data pointers such as "int *," "char *," etc. The following is a basic example of a...

3 minutes read.

Armstrong number using for loop in C++

What is For Loop? A for loop is a repetitive control structure that allows you to create a loop to execute a specific number of times efficiently. The syntax that can be...

4 minutes read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

What does Buffer Flush mean in C++

A buffer flush, to explain simple layman's terms, is nothing but the transfer of computer data which is being stored in a rentable temporary memory of your computer running either...

3 minutes read.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 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.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.