Static functions do not belong to an object because they cannot access the data elements of an object. They usually have the task of serving as an interface for the static variables. Among other things, this ensures that variables cannot be manipulated from outside. Static functions have in common with static variables that they belong to the class, but can be used independently of the number or existence of objects.
class ClassName {
public:
static ReturnType FunctionName(ParameterList);
};
static
: Keyword to declare a static function.ReturnType
: The data type of the value returned by the function.FunctionName
: The name of the static function.ParameterList
: List of parameters (can be empty).ReturnType ClassName::FunctionName(ParameterList) {
// Function body
}
‘ClassName::
‘: Specifies that the function belongs to ClassName
.
ClassName::FunctionName(arguments);
Called using the class name, not an object.
Here’s a complete example demonstrating a static function in a C++ class:
#include <iostream>
using namespace std;
class MathOperations {
public:
static int add(int a, int b);
static int multiply(int a, int b);
};
// Implementation of static functions
int MathOperations::add(int a, int b) {
return a + b;
}
int MathOperations::multiply(int a, int b) {
return a * b;
}
int main() {
// Calling static functions using the class name
cout << "Addition: " << MathOperations::add(5, 3) << endl;
cout << "Multiplication: " << MathOperations::multiply(5, 3) << endl;
return 0;
}
class MathOperations {
public:
static int add(int a, int b);
static int multiply(int a, int b);
};
Declares two static functions add
and multiply
.
int MathOperations::add(int a, int b) {
return a + b;
}
int MathOperations::multiply(int a, int b) {
return a * b;
}
Defines the behavior of add
and multiply
functions.
int main() {
cout << "Addition: " << MathOperations::add(5, 3) << endl;
cout << "Multiplication: " << MathOperations::multiply(5, 3) << endl;
return 0;
}
Calls the static functions using the class name MathOperations
and prints the results.
this
pointer.