Class Variables - Tryhardtocarry/2143-oop GitHub Wiki
A class variable is a variable that is shared among all objects of a class. class variables are stored in a single memory location and remain the same across all objects.
#include <iostream>
using namespace std;
class Car {
private:
string brand; // Instance variable
string model; // Instance variable
static int carCount; // Class variable
public:
// Constructor
Car(string b, string m) {
brand = b;
model = m;
carCount++; // Increments the shared car count
}
// Static function to get total car count
static int getTotalCars() {
return carCount;
}
// Function to display car details
void display() {
cout << "Car: " << brand << " " << model << endl;
}
};
// Initialize the static class variable outside the class
int Car::carCount = 0;
int main() {
// Creating Car objects
Car car1("Toyota", "Corolla");
Car car2("Honda", "Civic");
Car car3("Ford", "Mustang");
car1.display();
car2.display();
car3.display();
return 0;
}