class Car {
public:
Car() {
plate = "TestPlate";
};
void RegPlate() {
plate = Tommy.getNewPlate();
};
void CheckPlate() {
cout << plate << endl;
};
public:
staticclass Manager {
public:
Manager() {
numberOfCars = 88;
};
// static function
static string getNewPlate() {
++numberOfCars;
ostringstream temp;
temp << "AAA" << numberOfCars;
return temp.str();
};
private:
staticint numberOfCars; // static int
} Tommy;
private:
string plate;
};
//Car::Manager Car::Tommy; // global Tommy is not required
int Car::Manager::numberOfCars = 88; // global int is required
void main() {
Car myNewCar[10];
for (int i = 0; i < 10; i++) {
myNewCar[i].Tommy.getNewPlate(); // skip one plate number
myNewCar[i].RegPlate();
myNewCar[i].CheckPlate();
}
}
I have these two codes having the same output.
In code1, the inner class Car::Manager is static, hence all Car objects share the same Manager Tommy, which means Tommy has to be defined globally.
In code2, I would like to call Car::Manager::getNewPlate() without a Car object, so getNewPlate() is now static so as numberOfCars.
My question is that why in code2 Tommy does not need to be defined globally anymore? Only the static int is enough to compile without error.
If all properties of a class are static, then all instances of the class are "global". I would assume the compiler obviates the definition of a global instance of such a class, since all instances of it are already global.