c-plus-plus
  1. c-plus-plus-static-member-function

C++ Programs Static Member Functions

Static member functions in C++ are member functions that belong to a class rather than an instance of the class. They can be called without creating an object of the class and are static in the sense that they do not have access to non-static data members or member functions.

Syntax

class MyClass {
    public:
        static return_type static_function_name(parameters);
};

Static member functions are declared using the static keyword within the class definition.

Example

#include <iostream>
using namespace std;

class Counter {
    private:
        static int count;
    public:
        static void increment() {
            count++;
        }
        static int getCount() {
            return count;
        }
};

int Counter::count = 0;

int main() {
    Counter::increment();
    Counter::increment();
    Counter::increment();
    cout << "Count: " << Counter::getCount() << endl;
    return 0;
}

Output

Count: 3

Explanation

In the above example, we have defined a class called Counter that has a static data member called count. We have also defined two static member functions called increment and getCount that manipulate and return the value of count, respectively. We call the increment function three times using the class name and scope resolution operator (::) and then call the getCount function to print out the value of count.

Use

Static member functions are useful when you need to perform some task that does not involve individual objects of the class. They can be used to keep track of global state or to implement utility functions that do not need access to individual object data members.

Important Points

  • Static member functions can be called without creating an object of the class.
  • They are declared using the static keyword within the class definition.
  • Static member functions do not have access to non-static data members or member functions.
  • They can be used to keep track of global state or to implement utility functions.

Summary

Static member functions in C++ are a powerful feature that allow you to define functions that are associated with a class rather than individual objects. They can be used to keep track of global state or to implement utility functions that do not need access to individual object data members. They are declared using the static keyword within the class definition and don't have access to non-static data members or member functions.

Published on: