I've been having big problems in reproducing and finding the cause of a bug. The occurence seems entirely random, so I suspected an uninitialized variable somewhere. But then I found this piece of code:
CMyClass obj; // A
obj.DoStuff();
if ( somebool )
{
CMyClass obj; // B
obj.DoStuff();
}
obj.DoOtherStuff();
It seems as though DoOtherStuff() is either done on "B", or that B.DoStuff() sometimes actually works on A - i.e. i DoStuff() is actually called on the first obj.
Could this happen? I don't think I got a compiler warning (I've fixed the code now in hoping that it might help). It seems very likely that this piece of the actual code is where the bug I'm trying to find is, but there could of course be other reasons I haven't discovered yet.
The code, as written, should work. The first call to DoStuff() and the last call to DoOtherStuff() can only be sent to A.
The call to DoStuff() inside the if(somebool) { } block can only be sent to B.
From the standard:
3.3.2 Local scope
- A name declared in a block (6.3) is local to that block. Its potential scope begins at its point of declaration (3.3.1) and ends at the end of its declarative region.
And:
3.3.7 Name hiding
- A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2).
That being said, perhaps this is not what was intended by the author of that code. If the variables have the same name, perhaps the intent is to have only one instance of that variable, and the B instance created inside the loop is a mistake. Have you gone through the logic to see if a second instance makes sense?
Unless obj.DoStuff() makes a change to a some global object then as Valentin points out it should all be self contained within the scope of the if statement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With