Reputation: 5194
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;
}
Upvotes: 1
Views: 2225
Reputation: 208353
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 a typedef
to provide an aliased name Foo2
.
The third option would be:
typedef class Foo3 {
public:
void bar() {}
} Foo3;
That would create a class named Foo3
and create an alias Foo3
to 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:
class A {};
typedef class {} B;
typedef class C {} C;
void A(); // correct: no collision
//void B(); // error, identifier B already used with a different meaning!
//void C(); // "
namespace test {
void B();
void C();
void f() {
class A a; // creates variable of type ::A
A(); // calls function ::A
B(); // calls function test::B()
//class B b; // error: B does not denote a user-defined type name
C(); // calls function test::C()
class C c; // creates variable of type ::C
}
}
Upvotes: 6
Reputation: 3834
I believe that the second was necessary for C, but is really unnecessary for C++. Internally I belive that the second one is creating a unnamed class, and then creating a typedef for that, while the first is just creating the class.
I don't think that the typedef style class declaration is needed in c++ libraries.
Upvotes: -1