Static Members in C++ Classes

Static Members in C++ Classes

There are three static members in C++ classes. They are as follows:

1. Static local variables.
2. Static member variables.
3. Static member functions.


Static local variables

1. The variable made within block (generally function block) with static keyword is called static local variable. 
2. They are by default initialized to zero (0). 
3. Their lifetime is throughout the program.


For Example:-

void function()
{
static int num1;
};


Static member variables

1. The variable declared inside body of any class is called static member variable. 
2. It is also known as class member variable or class variable. 
3. It must be defined outside the class. 
4. It does not belong to any object but belong to whole class.
5. Any object of the class can use the same copy of class variable.
6. It can also be used with class name.


For Example:-

class Account
{
private:
int balance; //instance member variable.
static float rate; //static member variable or class variable.
};

float Account::rate = 3.5f; //defining class variable.


Static member functions

1. Function qualified with static keyword is called static member function.
2. It is also called class member function.
3. It can be invoked with or without object of the class.
4. It can only access static members of the class.


For Example:-

class Account
{
private:
int balance; //instance member variable.
static float rate; //static member variable or class variable.

public:
void setBalance(int num)
{
balance = num;
}

static void setRate(float r)
{
rate = r;
}
};

float Account::rate = 3.5f; //defining class variable.

int main()
{
Account A1, A2;
A1.setRate(4.5f); //when object is given.

Account::setRate(4.5f); //when no object is created.
}


<< Previous                                                                                      Next >>
Previous
Next Post »