Static Class Member Static Member Function

Estimated reading: 6 minutes 28 Views

Introduction

In C++, “static class members” and “static member functions” introduce class-level elements that are not associated with individual objects of the class.

#include <iostream>
#include <string>
using namespace std;
void f()
{
    static int x = 0;
    x++;
    cout << x << endl;
}
int main()
{
    f();
    f();
    return 0;
}

This C++ program defines a function f() that increments a static integer variable x each time it is called, and then prints the value of x to the standard output. The main() function calls f() twice.

Here’s what the program does:

  • The function f() is defined. It contains a static variable x initialized to 0.
  • Each time f() is called, it increments x by 1 and prints the new value of x.
  • In the main() function, f() is called twice.
  • When f() is called the first time, x is incremented from 0 to 1, and 1 is printed.
  • When f() is called the second time, x is incremented from 1 to 2, and 2 is printed.

Therefore, when you run the program, it should output:

1
2

Here’s what static does in this context:

  1. Preserves Value between Function Calls: When a variable is declared as static inside a function, its value persists between function calls. This means that the variable retains its value even after the function f() exits. In the example, the variable x retains its value between calls to f().
  2. Initialization: Static variables are initialized only once, at the start of the program execution. In this case, the static variable x is initialized to 0 the first time the function f() is called. Subsequent calls to f() do not reinitialize x.
  3. Storage Duration: Static variables have “static storage duration,” meaning they are allocated memory for the entire duration of the program’s execution. This memory is allocated in the data segment of the program.
  4. Scope: The scope of a static variable declared inside a function is limited to that function. It cannot be accessed from outside the function. In this example, x can only be accessed within the f() function.

Static Class Member

#include <iostream>
#include <cstring>
#include <string>
using namespace std;
//define how many objects are created 
class Student {
        static int count;
        char name[20];
        int first, second, final, total, ID;
    public:
        Student() //constructor 
        {
            strcpy(name, "No name");
            ID = 0;
            first = second = final = 0;
            count++;
            cout << "Numbers of students constructed: " << count << endl;
        }
}; //end of class
int Student::count = 0;
int main()
{
    cout << "\nConstruct 2 objects\n";
    Student S1, S2;
    cout << "\nConstruct 3 objects\n";
    Student St[3];
    return 0;
} //end of main

Class Definition (Student):

  • It defines a class Student with private data members name, first, second, final, total, and ID.
  • The count variable is declared as static within the class. This means it is shared among all instances of the Student class, and its value persists across multiple Student objects.

Constructor:

  • The class has a default constructor Student() which initializes the data members with default values.
  • In the constructor, the name is set to “No name”, ID is set to 0, and exam scores are set to 0.
  • Each time a Student object is constructed, the count variable is incremented, and the total number of constructed students is printed.

Static Member Initialization:

  • The count static member is initialized outside the class definition.

Main Function:

  • In the main() function, two Student objects (S1 and S2) are created using the default constructor. The program prints the number of students constructed after each object creation.
  • Then, an array St of three Student objects is created. Again, the program prints the number of students constructed after creating this array.

Output:

Construct 2 objects
Numbers of students constructed: 1
Numbers of students constructed: 2

Construct 3 objects
Numbers of students constructed: 3
Numbers of students constructed: 4
Numbers of students constructed: 5

The count static member variable is used to keep track of the total number of Student objects that have been created. Each time a Student object is constructed (i.e., when the constructor is called), the count is incremented. This allows the program to keep track of how many Student objects have been instantiated across the entire program execution.

Static Member Function

#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class Student {
        static int count;
        char name[20];
        int first, second, final, total, ID;
    public:
        static void print_count()
        {
            cout << "Students constructed: " << count << endl;
        }
        Student() //constructor 
        {
            strcpy(name, "No name");
            ID = 0;
            first = second = final = 0;
            count++;
            print_count();
        }
}; //end of class
int Student::count = 0;
int main()
{
    Student::print_count();
    cout << "\nConstruct 2 objects\n";
    Student S1, S2;
    cout << "\nConstruct 3 objects\n";
    Student St[3];
    return 0;
} //end of main

In this updated version of the program, a static member function print_count() has been added to the Student class. Here’s what the static keyword does in this context:

  • Static Member Function: The member function print_count() is declared as static. This means that it belongs to the class itself, rather than to individual instances (objects) of the class. Static member functions do not have access to non-static member variables or functions directly because they are not associated with any particular object.
  • Accessing Static Member Variables: Inside the static member function print_count(), the static member variable count is accessed directly. Since count is also static, it can be accessed without needing an instance of the class.
  • Accessing Static Member Function: Static member functions can be called using the class name followed by the scope resolution operator (::). For example, Student::print_count() calls the print_count() function of the Student class.
  • Usage: In the main() function, Student::print_count() is called before any Student objects are created. This demonstrates that static member functions can be called without the need for object instantiation.
  • Initialization and Increment: Inside the Student constructor, the count variable is incremented each time a new Student object is constructed. The print_count() function is called within the constructor to display the updated count after each object creation.

This program demonstrates the usage of a static member function to access a static member variable and provide functionality associated with the class itself, rather than individual objects of the class.

Share this

Static Class Member Static Member Function

Or copy link

CONTENTS
English