OOP: ADVANCED OOP TOPICS
Static Members
A static data member belongs to the class, not to each individual object.
Normal data member:
Each object gets its own copy.
Static data member:
All objects share one copy.
Complete Example
#include <iostream>
using namespace std;
class Student {
private:
int id;
static int count;
public:
Student() {
++count;
id = count;
}
void display() const {
cout << "Student ID: " << id << endl;
}
static int getCount() {
return count;
}
};
int Student::count = 0;
int main() {
Student s1;
Student s2;
s1.display();
s2.display();
cout << "Total students: " << Student::getCount() << endl;
return 0;
}
Output:
Student ID: 1
Student ID: 2
Total students: 2
Static Member Function
A static member function:
- Can be called using the class name.
- Can access static members directly.
- Cannot access non-static members directly because it has no
thispointer.
Example:
Student::getCount();
Why Static Data Is Defined Outside
In classic C++, a static data member is declared inside the class and defined outside the class.
class Student {
static int count;
};
int Student::count = 0;
Modern C++ also supports inline static data members, but the outside definition is still important for viva.
Viva Answer
A static data member belongs to the class and is shared by all objects. A static member function can be called using the class name and can access static members directly, but it cannot access non-static members directly because it has no this pointer.
Quick Check
- Does each object get a separate copy of a static data member?
- Can a static member function access
iddirectly in the example? - Why can we call
Student::getCount()without an object?