quote:And what reason would that be? I don''t think the compiler would do a random stuff like that. One time it would destroy objects and other times it would not.
I guess that when the loop finishes it moves to the next statement and for some reason the last object on the stack hasn''t been destroyed by scope,
I think this is the same scenario as C-string.
char* pchar = "Hello";
if ( pchar == "Hello" )
{
}
There is only one instance of "Hello" exists in the memory, thus the if statement above would yield true; a common misconception for newbies when comparing C-strings.
When you type in dog(), the compiler will create only one object in the stack for the whole execution of the program. Since OP calls this dog() multiple times in a loop, the constructor gets called multiple times and since this is the same object, it''s the same dog::val that gets incremented.