Member Variables - heshawacooray/OOP-Heshawa GitHub Wiki

Member Variables

Definition: Member variables are variables that are defined inside a class. They represent the state or properties of an object and can be classified into two types:

  • Instance Variables: These variables are tied to a specific object (instance of the class). Each object has its own copy of these variables.
  • Class Variables: These are variables that are shared across all instances of a class. They are declared with the static keyword and retain a single value, regardless of how many objects are created.
Type Instance Variables Class Variables
Definition Tied to a specific instance of a class. Shared among all instances of a class.
Memory Allocation Each object gets its own copy. One copy is shared among all objects.
Lifetime Exists as long as the object exists. Exists as long as the program runs.
Accessibility Accessed through an object instance. Accessed using the class name.

Example code for Instance Variables:

#include <iostream>
using namespace std;

class Car {
private:
    string brand; // Instance variable
    int year;     // Instance variable

public:
    // Constructor to initialize instance variables
    Car(string b, int y) {
        brand = b;
        year = y;
    }

    // Function to display car details
    void display() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car car1("Toyota", 2020);  // Creating an object of Car
    Car car2("Honda", 2018);   // Another object of Car

    car1.display();  // Displays: Brand: Toyota, Year: 2020
    car2.display();  // Displays: Brand: Honda, Year: 2018

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