Home  >  Article  >  Backend Development  >  Are static variables in member functions shared across all instances of a class?

Are static variables in member functions shared across all instances of a class?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-23 09:07:31214browse

Are static variables in member functions shared across all instances of a class?

Static Variables in Member Functions: Understanding Their Behavior

In C , static variables within member functions behave differently than instance variables. Let's explore how they work using an example:

Consider the following class:

class A {
   void foo() {
      static int i;
      i++;
   }
};

In this class, i is declared as a static variable within the foo member function. Static variables have a lifetime that persists throughout the entire program.

Now, let's consider what happens when multiple instances of class A are created:

A o1, o2, o3;

Is the static variable i shared among all instances of A, or does each instance have its own copy?

In C , static variables within member functions are shared among all instances of the class. This means that calling foo() on one instance of A increments the same i for all instances.

To illustrate this behavior:

o1.foo(); // i = 1
o2.foo(); // i = 2
o3.foo(); // i = 3

In this example, each instance of A calls the foo() function, incrementing the shared static variable i.

Therefore, unlike instance variables, which are unique to each instance, static variables in member functions are a single entity shared by all instances of a class. They maintain their values throughout the lifetime of the program.

The above is the detailed content of Are static variables in member functions shared across all instances of a class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn