Static Member Function C++

A static member function in a class is a function that belongs to the class, not an object.

  1. can be accessed without using an object of the class (while a non-static member function cannot)
  2. can be called by using an object of the class
  3. can only access static data members
  4. a static member function doesn’t have this pointer which points to the object of the class
#include <iostream> 
#include <string> 
using namespace std; 
 
class Hello 
{ 
public: 
private: 
    static string welcome; 
    string goodbye; 
 
public: 
    static void print() 
    { 
        cout << welcome << endl; //YES: will be printed out 
        cout << goodbye << endl; //NO: will NOT be printed out 
    } 
}; 
 
string Hello::welcome = "welcome here coder"; 
 
int main(){ 
    Hello::print();  //YES: okay to be called without using an object 
    Hello h; 
    h.print();  //YES: okay to be called by using the object 
    return 0; 
} 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

Source-IBMopen in new window
Source-ResearchGateopen in new window

Last Updated: 11/30/2021, 6:23:55 AM
Contributors: oddnaveed