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>
using namespace std;

class Student {
public:
    // Instance member variables (attributes)
    string name;
    int age;
    
    // Static member variable
    static int studentCount;

    // Constructor to initialize instance variables
    Student(string n, int a) {
        name = n;
        age = a;
        studentCount++;
    }

    // Method to display student details
    void displayDetails() {
        cout << "Student Name: " << name << ", Age: " << age << endl;
    }

    // Static method to access the static member variable
    static void displayStudentCount() {
        cout << "Total Students: " << studentCount << endl;
    }
};

// Initialize static member variable
int Student::studentCount = 0;

int main() {
    // 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 method
    Student::displayStudentCount();  // Total Students: 2

    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️