Static function

Static function is used to access static data members of a class.
Static function is called using class name and scope resolution operator. We do not need an object to call static function.

//Header file
class singleton {
    static singleton* m_instance;
    singleton() {}
    singleton& operator=(const singleton& );
    singleton(const singleton& );     
public:
    ~singleton() {}
    static singleton* getInstance();
};

//Source file

singleton* singleton::m_instance = NULL;
singleton* singleton::getInstance() {  //static function accessing static data member m_instance
    if (NULL == m_instance) {
        return new singleton;
    }


    return m_instance;
}


int main() {
    singleton* instance =
singleton:: getInstance(); // static function  called using class name and scope resolution operator.
    delete instance;
    return 0;
}

  • The above example is one of the typical example of singleton function used in singleton class. getInstance() is a static function which allocates a memory for static variable m_instance and return the same.
  • There is not object used to call static function.
  • Static functions do not have this pointer. This the reason that static function cannot be const function.
  • Static function cannot be virtual function as it is associated to class not to an object.


Related posts