Wednesday, February 22, 2012

static variables and static member functions in C++

In C++, there are two uses when static used for C++ classes namely static member variables and static member functions. To access static variables or member functions , no need to create the object. We can directly access by using scope resolution operator with class name. By default static member variable value is zero, need to assign manually for non-zero value.

class staticDemo
{
     public:
         static int stValue; // declaring the static variable
};

int staticDemo::stValue = 10; // initializing static variable

int main()
{
   cout<<"stValue  is "<<staticDemo::stValue; // accessing the static varaible
}
Static member functions: Whatever we discussed above is fine for publice data. If the static data variables are private, we cant access the data directly. So to access the static data, we need static member functions. static member fucntions have two interesting points. 
  • Static member functions dont have this pointer, because they dont have objects.
  • Static member functions can only access static member variables. They cant access non-static member variables.
class staticDemo

{
     private:
         static int stValue; // declaring the static variable
     public:
        static int getValue(); // static method declaration

};

int staticDemo::stValue = 20; // initializing static variable

int staticDemo::getValue()    // static method definition
{
    return staticDemo::stValue;
}

int main()
{

      cout<<"stValue  is "<<staticDemo::getValue(); // accessing the static varaible using static method

}

The basic differenc between non-static and static data is that former one is belongs to object and later one is belongs to class. So for static data to access, no need of object. because of this static data dont have this pointer. Where as for non-static data we need object to access. And each data in the object is different from the other object. Static data is class specific ans non-static data is object specific.


No comments:

Popular Posts