Static Methods - heshawacooray/OOP-Heshawa GitHub Wiki
Definition: Static methods in C++ are methods that belong to the class itself rather than to any particular instance. They are used when a method operates on class-level data or performs a function that doesn't require access to individual object data.
Example code:
#include <iostream>
using namespace std;
class Car {
private:
string brand;
int year;
static int totalCars; // Static data member
public:
Car(string b, int y) {
brand = b;
year = y;
totalCars++; // Increment totalCars for each new car
}
static int getTotalCars() {
return totalCars;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
// Initialize static member outside the class
int Car::totalCars = 0;
int main() {
Car car1("Toyota", 2020);
Car car2("Honda", 2018);
Car car3("Ford", 2022);
car1.display();
car2.display();
car3.display();
cout << "Total Cars: " << Car::getTotalCars() << endl;
return 0;
}