sonu said:
Hi All,
Pls clarify me what is the difference between static member and static
method in c.
pls some one reply me with Example.
You're thinking of C++, not C. Followups set to comp.lang.c++.
My C++ is still a bit weak, so don't consider this to be authoritative.
Static members and static methods do not belong to a particular class
instance, and are not referenced through a particular class instance.
Instead, you refer to them using the class name and scope resolution
operator ::. The best way to illustrate it is with an example:
#include <iostream>
using std::cout;
using std::endl;
class MyClass
{
public:
MyClass()
{
m_staticInstance++;
}
~MyClass()
{
m_staticInstance--;
}
// Instance method
int getInstanceValue()
{
return m_instance;
}
// Static method
static void setStaticInstance(int value)
{
m_staticInstance = value;
}
// Instance member
int m_instance;
// Static member
static int m_staticInstance;
};
// If you declare a static member inside of a
// class, you must provide a corresponding
// definition of it outside of the class;
// this is necessary since the member
// has to exist independently
// of any class instance.
int MyClass::m_staticInstance = 0;
int main(void)
{
MyClass instance0, instance1;
// Refer to instance members and methods through
// the instance.
instance0.m_instance = 100;
instance1.m_instance = 200;
cout << "instance0.m_instance: "
<< instance0.m_instance << endl
<< "instance1.m_instance: "
<< instance1.m_instance << endl
<< "instance0.getInstanceValue(): "
<< instance0.getInstanceValue() << endl
<< "instance1.getInstanceValue(): "
<< instance1.getInstanceValue() << endl;
// Refer to static members and methods through
// the class name.
cout << "MyClass::m_staticInstance: "
<< MyClass::m_staticInstance << endl
<< "MyClass::getStaticInstance(): "
<< MyClass::m_staticInstance << endl;
MyClass::m_staticInstance = 3;
// Refer to static members and methods through
// the class name.
cout << "MyClass::m_staticInstance: "
<< MyClass::m_staticInstance << endl
<< "MyClass::getStaticInstance(): "
<< MyClass::m_staticInstance << endl;
return 0;
}
And the output:
john@marvin ~/prototypes/C++/static_demo $ ./static_demo
instance0.m_instance: 100
instance1.m_instance: 200
instance0.getInstanceValue(): 100
instance1.getInstanceValue(): 200
MyClass::m_staticInstance: 2
MyClass::getStaticInstance(): 2
MyClass::m_staticInstance: 3
MyClass::getStaticInstance(): 3