Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

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:

#include <iostream>

using namespace std;

// Define a class named "MyClass"
class MyClass {
private:
    int x;   // Private member variable
public:
    // Constructor that initializes "x"
    MyClass(int x) : x(x) {}
    
    // Static member function that prints a message to the console
    static void printMessage() {
        cout << "This is a static function." << endl;
    }
    
    // Static member function that squares an integer and returns the result
    static int square(int num) {
        return num * num;
    }
};

// The main function
int main() {
    // Call the static member function "printMessage" using the class name
    MyClass::printMessage();
    
    // Call the static member function "square" using the class name
    // and assign the result to a variable named "result"
    int result = MyClass::square(5);
    
    // Print the result to the console
    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.

  • No labels