static variables and functions

Static Variables

Member variables of a class can be made static by using the static keyword. Static member variables only exist once in a program regardless of how many class objects are defined! One way to think about it is that all objects of a class share the static variables. Consider the following program:

#include<iostream>

using namespace std;

class time1
{
	public:
	static int a;
};

// assigning value to static variable
int time1::a = 100;

// any random function
int myFunction()
{
    // no need to pass it from any argument
    // value will be preserved in functions
    cout << time1::a << endl;

    return time1::a;
}

int main()
{
    // no need to call it from class objects
    // because now this variable is free
    // from object declarations to access it
    cout << time1::a << endl;

    time1::a = 200; // again accessing it

    cout << time1::a << endl;

    cout << "after function call" << myFunction();
    getchar();
    return 0;
}

Static functions

Non-static member functions can access all data members of the class: static and non-static. Static member functions can only operate on the static data members.
One way to think about this is that in C++ static data members and static member functions do not belong to any object, but to the entire class.

#include<iostream>

using namespace std;

class staticFunctions
{
	public:
	// static keyword with function definition
	static void myFunction()
	{
		cout << "inside myFunction";
	}
};

int main()
{
	// no need to declare an object of the staticFunctions class

	staticFunctions::myFunction();
	getchar();
	return 0;
}