How to Declare a Static Member Function in a Class in C++?
In C++, static functions are functions that are directly associated with a class so we can access the static function directly without creating an object of the class using the scope resolution operator. In this article, we will learn how we can declare a static function in a class in C++.
Declare a Static Function in a Class in C++
To declare a static member function, we can simply use the static keyword during the declaration of the function inside the class. Then we can use the scope resolution (::) operator to call the static function using the following syntax.
Syntax to Declare a Static Member Function
ClassName:: static_Function().C++ Program to Declare a Static Function in a Class
// C++ program to declare a static function in a class
#include <iostream>
using namespace std;
class Student {
private:
int marks;
int id;
string Name;
public:
// Declare a static function in the class
static void staticFunc() {
cout<<" Static function executed successfully"<<endl;
}
};
//Driver Code
int main() {
// Call the static function using scope resolution operator
Student::staticFunc();
return 0;
}
Output
Static function executed successfully