Member Variables - EduardoMSU/OOP-2143 GitHub Wiki
Member Variables in Object-Oriented Programming (OOP)
What are Member Variables?
Member variables are variables that are declared inside a class and are part of the class's definition. They are used to store the state or attributes of an object. Member variables can be either instance variables (specific to an object) or static variables (shared across all instances of the class).
Key Characteristics of Member Variables
Characteristic
Description
Class Association
Member variables are associated with a specific class and are part of the class's structure.
Storage of Object State
They represent the data or state of an object.
Access Modifiers
Member variables can have access modifiers (private, protected, public) to control visibility.
Instance or Static
They can be instance variables (belonging to individual objects) or static variables (shared by all objects of the class).
Default Initialization
Depending on the language, member variables may be initialized with default values if not explicitly set.
Types of Member Variables
Type
Description
Instance Variables
These variables hold the state of an individual object. Each object of the class has its own copy of instance variables.
Static Variables
Static member variables are shared by all instances of a class, meaning they hold the same value for all objects.
Syntax for Member Variables in C++
Example of Member Variables in a Class
#include<iostream>usingnamespacestd;classStudent {
public:// Instance member variables (attributes)
string name;
int age;
// Static member variablestaticint studentCount;
// Constructor to initialize instance variablesStudent(string n, int a) {
name = n;
age = a;
studentCount++;
}
// Method to display student detailsvoiddisplayDetails() {
cout << "Student Name: " << name << ", Age: " << age << endl;
}
// Static method to access the static member variablestaticvoiddisplayStudentCount() {
cout << "Total Students: " << studentCount << endl;
}
};
// Initialize static member variableint Student::studentCount = 0;
intmain() {
// Create objects of the Student class
Student student1("Alice", 20);
Student student2("Bob", 22);
// Access instance member variables
student1.displayDetails(); // Student Name: Alice, Age: 20
student2.displayDetails(); // Student Name: Bob, Age: 22// Access static member variable using static methodStudent::displayStudentCount(); // Total Students: 2return0;
}