What is the difference between these two pieces of code and what exactly does the "static" label accomplish? What does it do and why's it added on? What kind of difference does it make?
Thank you for any and all help, hope you're all having a nice day!
#include<iostream>
usingnamespace std;
class Employee{
private:
staticint number_of_employees;
public:
Employee(){
number_of_employees++;
cout << number_of_employees << endl;
}
};
//Declaring and Initializing
int Employee::number_of_employees = 0;
int main()
{
//Declaring
Employee Mr_A, Mr_B, Mr_C;
cout << endl;
cin.ignore();
return 0;
}
Output will be:
1 2 3
1
2
3
Note: "static variables should be declared outside of the class because a class is a logical abstract, it doesn't hold any allocated memory unless an instance (Object) of that class is declared. On the other hand static member variables should hold a memory location before any instance is created because it has to retain its value for all objects of a same type i.e. All objects of class A{ ... };"
You were not asking about the static member variable, were you?
1 2 3 4 5 6 7
class Foo
{
int x;
public:
void bar();
staticvoid gaz();
};
The usage:
1 2 3 4
Foo::gaz();
Foo f;
f.bar();
Static member variable is like a global variable with the exception that you can limit access to it by making it non-public.
Static member function is like a standalone function, except it can access members of the class (and you can limit who can call it). However, the gaz() above cannot access f.x, because it doesn't have reference to object f.
The important takeaway is this: Static Variables allow you to store the number of instances that exist in a certain class - ex: suppose you have a enemy class and you want to know how many enemy objects have been instantiated from that class, you could use a static data member to get this number. (increment it in the constructor of course...)
Static Functions also exists for the entire class and they are often written to work with static data members; static functions cannot access non-static data members.