(C++) static
March 10, 2018 ยท View on GitHub
Keyword enabling in-class or in-function static variables or create static member function.
A common use of static is when you want to keep track of how many instances a class has:
#include <iostream>
class instance_counter
{
static int m_n_instances;
public:
instance_counter()
{
++m_n_instances;
std::cout << "Constructed an instance."
<< "Now there are " << m_n_instances << ".\n";
}
~instance_counter()
{
--m_n_instances;
std::cout << "Destructed an instance."
<< "Now there are " << m_n_instances << ".\n";
}
};
int instance_counter::m_n_instances = 0;
int main()
{
instance_counter one, two, three, four,five;
}
Advice
Notes to self
- When in doubt if a variable should be static or not, do not make it static: I note that I do change variables from static to non-static, but never the other way around