2079 6

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]

Object Oriented ProgrammingChapter 4: Pointers, References, and Memory ManagementStatic data members and static functions

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 static inside 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 this pointer
  • 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

FeatureStatic Data MemberStatic Member Function
Shared among objectsYesN/A
Accessed via class nameYesYes
Needs object to callNoNo
Can access non-static membersN/ANo
this pointer availableN/ANo

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.