Apparently,
For reasons that reach into the prehistory of C, it is possible to declare a struct and a non-struct with the same name in the same scope. - (Bjarne Stroustrup - The C++ Programming Language. 4th Edition)
For example:
struct Ambig {};
// the struct must be referred to with the prefix struct
void Ambig(struct Ambig* buf) {}
I'm just curious what the initial reason was? Without understanding, it seems like an example of bad language design, that causes ambiguity and is confusing.
The reason, as stated in your quote from Stroustrup, is
historical. In C, you must always prefix the name of the
struct with struct
; the name of the struct (like the name of
unions or enums) is called a tag, and lives in a completely
different name space than other symbols. So things like:
struct stat
{
// ...
};
int stat( char const* filename, struct stat* buf );
are perfectly legal. (The above is, in fact, part of Posix).
In C++, the name of a class (declared with class
, struct
or
union
) or an enum is in the same namespace as everything else,
and unlike in C, you can write things like:
struct MyClass {};
MyClass variableName;
This would not be legal C. In C, the second line would have to be:
struct MyClass variableName;
The problem is that C++ needs to be able to use interfaces
defined in C (like the Posix interface, above). So C++ defines
some special rules to allow it: you can give a variable or
a function and a class type the same name. When you do, the
variable or function name has precedence, and hides the class
name, except in "elaborated type specifiers" (i.e. class
,
struct
, union
or enum
, followed by a symbol), where
non-type names are ignored in the lookup.
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