In C++, a static member function is a member function of a class that belongs to the class itself, rather than to any particular instance of the class. Static member functions are not associated with any object of the class and can be called using the class name, without needing an object of the class.
Here's an example of a static member function:
class MyClass { private: int x; public: MyClass(int x) : x(x) {} static void printMessage() { cout << "This is a static function." << endl; } static int square(int num) { return num * num; } }; int main() { MyClass::printMessage(); int result = MyClass::square(5); cout << result << endl; return 0; }
In this example, we have defined a class MyClass
with a private member x
. We have also defined two static member functions: printMessage
and square
. printMessage
is a void function that simply prints a message to the console, while square
takes an integer argument and returns its square.
In the main
function, we call printMessage
and square
using the class name, without needing an object of the class.
Static member functions are useful when you need to perform operations that don't depend on any particular instance of the class, or when you need to access static data members of the class. They can be used to perform utility functions, or to implement factory methods that create objects of the class.
Note that static member functions can only access static data members of the class, and not the non-static members.