In depth analysis of static member functions in C++ programming

  • 2020-05-05 11:37:17
  • OfStack

C++ static member function

Like a data member, a member function can be defined as static, which is defined by adding static to the front of the declared function in the class. Such as


  static int volume( );


Like static data members, static member functions are part of a class, not of an object.

To call a common static member function outside a class, use the class name and the field operator ":". Such as


  Box::volume( );


It also actually allows you to call static member functions, such as
, by object name


  a.volume( );


This does not mean that the function belongs to the a object, but only to the a type.

Unlike static data members, static member functions are not used to communicate between objects, but to handle static data members.

We know that when a member function of an object (a non-static member function) is called, the system assigns the starting address of the object to the this pointer of the member function. While the static member function does not belong to an object, it is independent of any object, so the static member function does not have this pointer. Since it does not point to an object, there is no default access to non-static members in an object (that is, no object name is specified when a data member is referenced).

It can be said that the fundamental difference between a static member function and a non-static member function is that a non-static member function has an this pointer, while a static member function does not have an this pointer. This determines that static member functions cannot access non-static members in this class.

Static member functions can directly refer to static data members in this class, because static members are also members of the class and can be directly referred to. In C++, static member functions are used to access static data members rather than non-static members.

Suppose you have the following statement in a static member function:


  cout<<height<<endl; // if height Has been declared as static , then refer to the static member in this class, legal 
  cout<<width<<endl; // if width Non-static data member, illegal 


However, it's not that you can never refer to a non-static member of this class, it's just that you can't access it by default because you don't know which object to look for.

If you must refer to a non-static member of the class, you should add the object name and the member operator "." Such as


  cout<<a.width<<endl; // References this class object a Is a non-static member of 


This statement is valid assuming that a has been defined as an Box class object and is valid in the current scope.

Here's an example of how to refer to a non-static member.

Application of static member functions.


#include <iostream>
using namespace std;
class Student          // define Student class 
{
public:
  Student(int n,int a,float s):num(n),age(a),score(s){ }   // Define the constructor 
  void total( );
  static float average( );   // Declare static member functions 
private:
  int num;
  int age;
  float score;
  static float sum;      // Static data member 
  static int count;      // Static data member 
};
void Student::total( )           // Define non-static member functions 
{
  sum+=score;              // Accumulative total score 
  count++;                // The total number of people counted 
}
float Student::average( )         // Define static member functions 
{
  return(sum/count);
}
float Student::sum=0;           // Initialize the static data member 
int Student::count=0;           // Initialize the static data member 
int main( )
{
  Student stud[3]={           // Define and initialize an array of objects 
   Student(1001,18,70),
   Student(1002,19,78),
   Student(1005,20,98)
  };
  int n;
  cout<<"please input the number of students:";
  cin>>n;                // Enter the average scores of the top students 
  for(int i=0;i<n;i++)         // call 3 time total function 
   stud[i].total( );
  cout<<"the average score of "<<n<<" students is "<<Student::average( )<<endl;
  // Call the static member function 
  return 0;
}

The result is:


please input the number of students:3 � 
the average score of 3 students is 82.3333

A few notes on static member function members:
The stud object array is defined in the main function. In order to simplify the program, only three elements are defined, each containing three students' data. The purpose of the program is to find the total score of the n students specified by the user, and then the average score (n is entered by the user).
Student class defines the two static data members sum (score) and count (cumulative statistics the number of students), it is because of these two data member value is to accumulate, they are not only belongs to a certain object elements, but by the Shared object element, it can be seen that their values are changing, and no matter for which object element are the same, and always don't release the memory space.
total is a public member function that accumulates a student's grades into sum. Public member functions can refer to general data members in the object (non-static data members) or to static data members in the class. score is a non-static data member, sum and count are static data members.
average is a static member function that directly references private static data members (without having to add class or object names) and returns the average of the results.
In the main function, the total function is referred to by the object name (now the object array element name), and the average function is referred to by the class name or object name.
Think about it, what if I didn't define the average function as a static member function? Can the program be compiled? What changes need to be made? Why use static member functions? Analyze the reasons.

C++ static static member variable and static member function
In general, if there are N objects of the same kind, then each object has its own member variables, and the member variables of different objects have their own values, which are irrelevant to each other. But sometimes we want to have one or more member variables that are common to all objects, so that data can be Shared.

Global variables can be used to share data. For example, if there are multiple functions in a program file, each function can change the value of the global variable, and the value of the global variable is Shared by each function. However, the security of using global variables cannot be guaranteed. Since the value of global variables can be changed freely everywhere, it is very possible to accidentally fail, and the value of global variables will be changed, resulting in the failure of the program. Therefore, global variables are rarely used in real development.

If you want to share data between multiple objects of the same class, and you don't use global variables, you can use static member variables.
static static member variable

A static member variable is a special member variable that begins with the keyword static. For example:


class Student{
private:
  char *name;
  int age;
  float score;
  static int num; // will num Is defined as a static member variable 
public:
  Student(char *, int, float);
  void say();
};

This code declares a static member variable, num, to count the number of students.

The static member variable belongs to a class, not to a specific object, which means that even if multiple objects are created, only one portion of memory is allocated to num, and all objects use the data in that memory. When an object modifies num, it also affects other objects.

The static member variable must be initialized before it can be used, otherwise the link fails. For example:


int Student::num; // Initialize the 


You can also assign an initial value at initialization:


int Student::num = 10; // Initialize and assign 


You can initialize without static, but you must have a data type. static member variables modified by private, protected, public can be initialized in this way.

Note: the memory space of the static member variable is allocated neither when the class is declared nor when the object is created, but when it is initialized.

static member variables can be accessed either by object or by class. Access by class is in the form


  Box::volume( );
0


For example:


  Box::volume( );
1


These two approaches are equivalent.

Note: the static member variable is independent of the object and does not occupy the memory of the object. Instead, it is allocated memory in addition to all objects and can be accessed even if no object is created.

Here's a complete example:


  Box::volume( );
2

Results:


 Xiao Ming's age is  15 , the result is  90 (the current total 1 Student) 
 Li lei's age is  16 , the result is  80 (the current total 2 Student) 
 Zhang hua's age is  16 , the result is  99 (the current total 3 Student) 
 Wang kang's age is  14 , the result is  60 (the current total 4 Student) 

In this example, num is declared as a static member variable, and every time an object is created, the constructor is called to increment the value of num by 1. Anonymous objects are used because each time an object is created, its say function is used and nothing more is done. Be aware, however, that there is a memory leak risk with anonymous objects.

A few notes on static data members:
1) a class can have one or more static member variables, all objects share these static member variables, can refer to it.

2) static member variables, like ordinary static variables, allocate memory in the static data area at compile time and release it at the end of the program. This means that the static member variable does not allocate memory with the creation of the object, nor does it free memory with the destruction of the object. Ordinary member variables allocate memory when the object is created and free it when the object is destroyed.

3) static member variables must be initialized and can only be done outside the class. For example:


  Box::volume( );
4


An initial value may or may not be assigned upon initialization. If no value is assigned, it will be initialized by default, usually 0. Variables in the static data area all have default initial values, while variables in the dynamic data area (heap area, stack area) default to garbage values.

4) static member variables can be accessed either by object name or by class name, subject to access restrictions for the private, protected, and public keywords. When accessed by object name, the same memory is accessed for different objects.
static static member function

In a class, static can declare static member functions as well as static member variables. Normal member functions can access all member variables, while static member functions can only access static member variables.

We know that when a member function of an object (a non-static member function) is called, the system assigns the starting address of the current object to the this pointer. While the static member function does not belong to an object, it is independent of any object, so the static member function does not have this pointer. Since it does not point to an object, non-static members of that object cannot be accessed.

It can be said that the fundamental difference between a static member function and a non-static member function is that a non-static member function has an this pointer, while a static member function does not have an this pointer. This determines that static member functions cannot access non-static members in this class.

Static member functions can directly refer to static data members in this class, because static members are also members of the class and can be directly referred to. In the C++ program, static member functions are primarily used to access static data members, not non-static members.

To call the static member function of the public attribute outside of the class, use the class name and the field resolver ":". Such as:


  Box::volume( );
5

Of course, you can also call static member functions by object name, such as


  Box::volume( );
6

The following is a complete example of obtaining a student's grade point average through a static member function:


  Box::volume( );
7

Results:


 Xiao Ming's age is  15 , the result is  90 (the current total 1 Student) 
 Li lei's age is  16 , the result is  80 (the current total 2 Student) 
 Zhang hua's age is  16 , the result is  99 (the current total 3 Student) 
 Wang kang's age is  14 , the result is  60 (the current total 4 Student) 
 Average score:  82.25

In the above code, num and total are declared as static member variables and getAverage as static member functions. In the getAverage function, only two static member variables total and num are used.


Related articles: