Home >Backend Development >C++ >How do static variables in member functions behave across different instances of a class?

How do static variables in member functions behave across different instances of a class?

Susan Sarandon
Susan SarandonOriginal
2024-11-09 09:06:01874browse

How do static variables in member functions behave across different instances of a class?

Static Variables in Member Functions

Consider the following class:

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

When dealing with static variables within member functions in C , it is crucial to understand how they behave across instances.

Multiple Instances and Static Variables

Contrary to the assumption that each instance would possess its own copy of the static variable, in this specific scenario, there will be only one copy of static int i within the entire program. This is because class A is a non-template class, and A::foo() is a non-template function.

Instance Impact on Static Variable

Regardless of which instance of A invokes the foo() method, the shared static variable i will be affected. For instance, if you declare multiple instances of A like this:

A o1, o2, o3;

Calling foo() on any of these instances will increment the i variable:

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

In conclusion, static variables in member functions are shared across all instances of the class, allowing any instance to access and modify the same value.

The above is the detailed content of How do static variables in member functions behave across different 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