Class Variables - EduardoMSU/OOP-2143 GitHub Wiki
Class variables are attributes that are shared among all instances of a class. Unlike instance variables (specific to each object), class variables have the same value across all objects unless explicitly changed. They are typically used to store data or behavior that is common to all instances of the class.
Characteristic | Description |
---|---|
Shared Across Instances | The value of a class variable is shared and the same for all instances of the class. |
Defined Using static |
In many programming languages (like C++ or Java), class variables are defined using the static keyword. |
Accessed via Class Name | Class variables can be accessed using the class name or an instance of the class. |
Stored in Memory Once | Only one copy of the variable is stored in memory, regardless of the number of instances. |
Common for All Objects | Useful for constants, counters, or shared properties that should be consistent across objects. |
Below is an example of using class variables in C++.
#include <iostream>
#include <string>
class Student {
private:
std::string name; // Instance variable
int age; // Instance variable
// Static class variable
static int totalStudents;
public:
// Constructor
Student(const std::string& studentName, int studentAge) : name(studentName), age(studentAge) {
totalStudents++; // Increment class variable
}
// Destructor
~Student() {
totalStudents--; // Decrement class variable
}
// Static method to get the total number of students
static int getTotalStudents() {
return totalStudents;
}
// Method to display student details
void displayInfo() const {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
// Initialize the static class variable
int Student::totalStudents = 0;
int main() {
Student s1("Alice", 20);
Student s2("Bob", 22);
std::cout << "Total Students: " << Student::getTotalStudents() << std::endl;
{
Student s3("Charlie", 19);
std::cout << "Total Students: " << Student::getTotalStudents() << std::endl;
} // s3 goes out of scope here, and the destructor is called
std::cout << "Total Students after scope ends: " << Student::getTotalStudents() << std::endl;
return 0;
}