Let's say one has a class Foo such as
class Foo {
public:
void bar();
operator bool() const { return true; }
};
then one can do
if(Foo foo = Foo())
{
if(Foo foo = Foo())
{
foo.bar();
}
}
Now I'm having trouble grasping the scope resolution going on here (I would've expected a compiler error for redeclaring foo).
I expect foo.bar() to execute on the second foo (its scope is "closer") but am I garanteed that it's actually a different object than the first foo? Furthermore, are they each independently disposed (their destructor called) at the end of their respective if blocks?
The use of if statements and class object initialization in your example tends to obscure the relevant point, which is that declarations in inner scopes are perfectly legal and hide declarations of the same name in outer scopes.
A perhaps clearer example:
The output is:
Note that the inner and outer
x
s aren't even of the same type.Though this is legal, it's usually not a good idea; the compiler has no problem with it, but it can be confusing to human readers. If you compile with
g++ -Wshadow
, you'll get warnings:C++ is quite happy for you to declare a variable with the same name, as long as it is inside a nested scope so there is no ambiguity.
You are correct
Yes
Yes
Correct.
Yes.
Yes, you've got it.