STATIC DATA MEMBERS & STATIC MEMBER FUNCTIONS
Static data members & static
member functions (methods):-
A static data member is a
class variable shared by all objects of that class.
Key
Characteristics
- Only
one copy
exists for the entire class (not per object).
- Shared
by all instances of the class.
- Stored
in global/static memory, not inside objects.
- Must
be declared inside the class and defined outside the class.
- Accessed
using:
- Object:
obj.x
- Class
name: ClassName::x (recommended)
Use of Static Data
Members
·
Maintain
common information for all objects.
·
Use
as counters (e.g., number of objects created).
·
Use
as constants inside class (static const).
Example (Static
Data Member)
#include <iostream>
using namespace std;
class Student {
static int count; // declaration
public:
Student() {
count++; // increase when object created
}
static int getCount() {
return count;
}
};
// definition outside class
int Student::count = 0;
int main() {
Student s1, s2, s3;
cout << "Total students: " << Student::getCount();
return 0;
}
OUTPUT
Total students: 3
STATIC MEMBER FUNCTIONS (METHODS)
A static member function:
- Belongs
to the class, not to any object.
- Called
without creating an object.
- Access
only static data members, not normal members.
Key Features
No, this pointer is available
Access only static members
Usually used to manipulate static data members
Access using:
- ClassName::function()
(preferred)
- or
through object
Example (Static Member Function)
#include <iostream>
using namespace std;
class Test {
private:
static int value;
public:
static void setValue(int v) {
value = v; // allowed
// x = 5; // ❌
not allowed (x is non-static)
}
static void showValue() {
cout << "Value = "
<< value << endl;
}
};
int Test::value = 0;
int main() {
Test::setValue(50);
Test::showValue();
return 0;
}
OUTPUT
Value = 50
SUMMARY TABLE
|
Feature |
Static Data Member |
Static Member Function |
|
Belongs to |
Class |
Class |
|
copies |
One per class |
Only one function |
|
Need an object |
No |
No |
|
Can access |
Static + Non-static |
Only static |
|
Uses |
Counters, Shared values |
Utility functions |
0 Comments