The question is pretty straightforward. To further clarify, what exactly is the difference between Foo1 and Foo2 in the code below in terms of the way they are declared (e.g. one using class Foo1 { ... }; and the other using typedef class { ... } Foo2;)?
class Foo1 {
public:
void bar() { }
};
typedef class {
public:
void bar() { }
} Foo2;
int main()
{
Foo1 f1;
f1.bar();
Foo2 f2;
f2.bar();
return 0;
}
The difference is subtle. In the first case you are creating a class with name
Foo1, while in the second case you are creating an annonymous class and using atypedefto provide an aliased nameFoo2.The third option would be:
That would create a class named
Foo3and create an aliasFoo3to refer to it.The subtleties are in how identifiers are handled in the language. When an identifier is present in the code the compiler will perform lookup to know what it means. The lookup will check in each scope, first in the global identifier space where most symbols (excluding user defined types) are defined, if it fails to locate the identifier there it will then look in the user-defined identifier space. User defined types belong to the second identifier space, while
typedef-ed names are present in the first group. Only if both lookups fail, the compiler will move on to the next enclosing scope.To provide a simple test case where the differences are notable: