Static member function in C++ with example
Today we are going to see the static member function in C++ with example.
Static member function
A static member function is a special function in a programming language, which is to access only static data members and other static member functions. There is only one copy of the static member no matter how many objects of a class are created.
- Also, read: Read data from CSV file in C++
A static member is shared by all objects of the class made. There is also one more highlighting feature of static data that it is initialized to zero when the first object is created. The static member functions are accessed using the only class name and the scope resolution operation :: .
C++ code example
Below is our C++ program to let you know what is static member function:
#include <iostream> using namespace std; class notebook { static int page_number; public: static int value() { return page_number; } }; int notebook::page_number=1; int main() { cout << "Number ="<<notebook::value()<< endl; return 0; }
The program is going to work like this:-
- First, we have to create a class notebook.
- The class notebook contains a static variable and a static member function.
- The static function returns the static member which is called in main.
- The static function is called using a class name with static member functoin name and :: sign.
If we run the program, then it will give the output which is given below:
Number=1
Leave a Reply