C++ - Static Functions
Static functions in a file restricts the access level to the functions on that file only.
Example for static function is given below:
#include <iostream>
static const char* GetWelcomeMessage()
{
static char msg[] = "Welcome to my static function";
return msg;
}
int main()
{
// GetWelcomeMessage can only be accessed in the current .CPP file
std::cout << GetWelcomeMessage();
// It will display Welcome to my static function as output
}
Can I have a static function in a class? Of course, YES. You can have any number of static function. If it is a public static function, you do not even need any class object to access the static member function. You can access it by <class name>::<static function name>.
A typical example for static function is singleton class. static MySingletonClass* GetInstance() is a static member function in the class and it is used in the main function.
#include <iostream>
class MySingletonClass {
private:
int m_nValue;
MySingletonClass() { };
MySingletonClass(const MySingletonClass& other);
const MySingletonClass& operator = (const MySingletonClass& other);
public:
static MySingletonClass* m_pMySingletonClass;
static MySingletonClass* GetInstance()
{
if(m_pMySingletonClass == NULL)
m_pMySingletonClass = new MySingletonClass();
return m_pMySingletonClass;
}
int GetValue() const { return m_nValue; }
void SetValue(int nVal) { m_nValue = nVal; }
};
MySingletonClass* MySingletonClass::m_pMySingletonClass = NULL;
int main()
{
// Accessing static function GetInstance()
MySingletonClass *p1 = MySingletonClass::GetInstance();
MySingletonClass *p2 = MySingletonClass::GetInstance();
// Both instances will point to the same object
p1->SetValue(100);
std::cout << p2->GetValue();
}
|