i just started programming in c++ this concept of static variable/function wasn\'t clear to me..why is this used and is there any other alternative of this!!!
why do we have to declare static in class and then assign the value outside the class!!!
Because it's merely DECLARED in the class, it is not DEFINED.
The class declaration is merely a description of the class, no memory is allocated until of object of that class is defined.
If instances of the class can be defined in many modules, and the memory for allocated in many places, where do you put the one instance of the static data members? Remember, the class declaration can & will be included in many source files of the application.
C++ has the "ODR" (which I insist should be the "1DR"): The "One Definition Rule". A data item can be DECLARED many times, but must be DEFINED exactly once. When you assign the value outside the class, the assignment part is actually irrelevant, it's the definition of the member that's important:
class A
{
static int MyInt; // Declaration
};
int A::MyInt; // Definition