A static data member is a variable shared by all objects of a class. static keyword is used to declare the static variable. Only one copy of the variable exists. If one object changes it, all objects see the changed value.
Suppose a school has 500 students.
The school name is common to all students, so it can be stored as a static data member.
class ClassName
{
public:
static dataType variableName;
};
dataType ClassName::variableName = value;
Whenever an object is created, the count increases. Since all objects share the same count variable, we use a static data member.
Program example 1 of using static variable
#include <iostream>
using namespace std;
class Student
{
public:
static int fee; // Declaration
};
// Definition
int Student::fee = 2000;
int main()
{
Student s1, s2;
cout << “Fee of Student 1 = ” << s1.fee << endl;
cout << “Fee of Student 2 = ” << s2.fee << endl;
return 0;
}
Example 2
#include <iostream>
using namespace std;
class Student
{
public:
static int count;
Student()
{
count++;
}
};
int Student::count = 0;
int main()
{
Student s1;
Student s2;
Student s3;
cout << “Total Objects = ” << Student::count;
return 0;
}
Output:
Total Objects = 3
Static function is
Syntax of static member function
class ClassName
{
public:
static void functionName()
{
// code
}
};
Calling
ClassName::functionName();
Program Example 1:
A college has a common exam fee for all students. The fee is stored as a static data member, and a static function is used to display it.
#include <iostream>
using namespace std;
class Student
{
public:
static int fee; // Static data member
static void showFee(); // Static function
};
int Student::fee = 2000;
// Definition of static function
void Student::showFee()
{
cout << “Exam Fee = ” << fee;
}
int main()
{
Student::showFee(); // Calling without object
return 0;
}
Output:
Exam Fee = 2000