BIT153 ยท 2079 ยท 5 marks
What is the task of static data members and function? Illustrate with an example.
What is the task of static data members and function? Illustrate with an example. [5]
Quick answer
A static data member is a class variable that is shared among all objects of that class. Unlike regular data members (which have separate copies for each object), only one copy of a static data member exists, regardless of how many objects are created.
Static Data Members and Static Member Functions in C++
Static Data Members
Key characteristics:
- Declared with the keyword
staticinside the class - Defined and initialized outside the class (in global scope)
- Shared by all objects of the class
- Exists even if no object is created
Static Member Functions
A static member function can be called without creating any object of the class. It can only access static data members and other static member functions.
Key characteristics:
- Declared with the keyword
static - Called using the class name and scope resolution operator (
::) - Does not have access to
thispointer - Cannot access non-static members directly
Example
#include <iostream>
using namespace std;
class Student {
private:
int rollNo;
static int count; // static data member: shared by all objects
public:
Student(int r) {
rollNo = r;
count++; // incremented each time an object is created
}
// static member function
static void showCount() {
cout << "Total Students: " << count << endl;
}
void showRoll() {
cout << "Roll No: " << rollNo << endl;
}
};
// Definition and initialization of static data member (outside class)
int Student::count = 0;
int main() {
Student::showCount(); // called without any object -> Total Students: 0
Student s1(101);
Student s2(102);
Student s3(103);
s1.showRoll(); // Roll No: 101
s2.showRoll(); // Roll No: 102
Student::showCount(); // called using class name -> Total Students: 3
return 0;
}
Output:
Total Students: 0
Roll No: 101
Roll No: 102
Total Students: 3
Summary Table
| Feature | Static Data Member | Static Member Function |
|---|---|---|
| Shared among objects | Yes | N/A |
| Accessed via class name | Yes | Yes |
| Needs object to call | No | No |
| Can access non-static members | N/A | No |
this pointer available | N/A | No |
Task in short: Static data members maintain common/shared state across all objects (e.g., counting objects), while static member functions provide utility operations that belong to the class as a whole rather than to any individual object.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.