I don't usually write this way but I've seen one code base where it's almost everywhere, e.g:
class prettyClass
{
// just class stuff
};
int main()
{
class prettyClass obj; // class?
return 0;
}
I don't usually write this way but I've seen one code base where it's almost everywhere, e.g:
class prettyClass
{
// just class stuff
};
int main()
{
class prettyClass obj; // class?
return 0;
}
In C, the tags of structures live in a different namespace to other identifiers. So unless one introduces an alias, they must write struct T
for the type name. In C++ (where class
and struct
are of the same underlying concept) it was made so that the tag is automatically introduced as a regular identifier.
However, there is one behavior in C that had to be accounted for. You could have something like this:
struct prettyThing
{
// data
};
void prettyThing();
And there's no ambiguity, due to the different namespaces. So C++ preserves this behavior. One could also have:
class prettyThing
{
// members
};
void prettyThing();
Without ambiguity, the class name is hidden by the other identifier. It is only accessible with an elaborated-type-specifier, i.e. class prettyThing
. That's one practical reason for why one may write the declaration as you see. And it's not academic, consider the POSIX stat
and struct stat
pair.
But... unless you are interfacing with C code that was originally written with the C notion in mind, there is no reason to write new C++ code that way.
One may wonder why it wasn't kept the same for types declared with struct
and simply disallowed for types declared with class
. To understand that, it's best to reiterate and remember that class
es and struct
ures are really meant to be the same thing in C++ (save for default access specifier). The following is all valid C++:
struct thing1; // forward declare
class thing1 {
// define
};
struct thing2 {
// define
};
class thing2 object;
Either keyword can be used in the elaborated-type-specifier, they are completely interchangeable in standard C++1.
1 - Microsoft ABI behaves as a bit of an oddball here, though.