Instance Variables - heshawacooray/OOP-Heshawa GitHub Wiki

Instance Variables

Definition: Instance variables, also known as member variables or non-static data members, are variables that are associated with a specific object (instance) of a class. Each object of the class has its own independent copy of the instance variables.

Example code:

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

public:
    Car(string b, int y) {
        brand = b;
        year = y;
    }

    void display() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    Car car1("Toyota", 2020);  
    Car car2("Honda", 2018);   

    car1.display();  
    car2.display();  

    return 0;
}