#include "Car.hpp" void f() { Car a; for (int i = 0; i < 10; ++i) { Car b; <-- 1 // ... } <-- 2 // ... } <-- 3 int main() { f(); }
The line labeled 1: Create a Car object on each iteration is within the loop body, so a distinct Car object that is local to the loop body is created on each iteration. Note that C++ allows loop variables (int i in the example) to be created inside the for parameters. Loop variables that are declared this way are local to the loop: they cannot be accessed after the } that terminates the for loop. This means that a subsequent for loop could use the same loop variable. Note that this is a new language feature, and compilers may not uniformly support this rule in all cases. Also notice that, unlike C, variables do not have to be declared right after a { . It is not only allowable but also desirable to declare C++ variables just before they are first used. Doing so allows their initialization to be bypassed if the section of code they are in is bypassed, and it allows the introduction of other runtime variables in their initialization if the code is not bypassed. So there is never anything to lose, indeed there is sometimes something to gain, by declaring at first use. |