Instance Variables - EduardoMSU/OOP-2143 GitHub Wiki
Instance variables are variables that are associated with a particular object (instance) of a class. Each object has its own copy of the instance variables, which hold the state or data unique to that object. Instance variables are typically declared inside a class but outside of any method, constructor, or destructor.
Characteristic | Description |
---|---|
Object-Specific | Each object has its own set of instance variables, meaning each object can have different values. |
State Representation | Instance variables typically represent the state of an object (e.g., attributes like color, size, etc.). |
Declared Inside Classes | They are declared inside the class definition, but outside any methods, constructors, or destructors. |
Access Modifiers | Instance variables can have access modifiers like private , protected , or public to control access. |
Lifetime | Instance variables exist as long as the object exists and are destroyed when the object is destroyed. |
#include <iostream>
using namespace std;
// Class definition
class Car {
public:
// Instance variables (attributes)
string make;
string model;
int year;
// Constructor
Car(string m, string mo, int y) {
make = m;
model = mo;
year = y;
}
// Method to display the car details
void displayDetails() {
cout << "Car Make: " << make << ", Model: " << model << ", Year: " << year << endl;
}
};
int main() {
// Create an object of class Car
Car car1("Toyota", "Corolla", 2020);
// Accessing instance variables and methods
car1.displayDetails(); // Car Make: Toyota, Model: Corolla, Year: 2020
return 0;
}