Reputation: 3564
Is there any significance behind allowing the visibility of nested structures outside the structure in C but not in C++? I did not find any reference or relevance.
struct a
{
struct b{
};
};
int main(){
struct b var; // allowed in C not in C++.
}
Upvotes: 28
Views: 16491
Reputation: 355069
It is valid in C because C has a single namespace in which all nonlocal types (i.e., types not declared in functions) are defined; there is no scoping of types using namespaces or nesting.
In C++, type b
is nested as a member of class a
, so its name must be qualified with the scope in which it is declared.
Upvotes: 35
Reputation: 1612
You cannot declare anything without a scope in C++ In your example struct b lies inside the struct a, compiler doesn't know where to find struct b
you have to use
struct a :: b var;
In C there is no restriction for scope, but C++ ensures a restriction
Upvotes: 4
Reputation: 1054
I believe the ability to reference nested structures outside of the structure was removed in C++ to improve data hiding. If you need to access a nested struct externally, then it probably shouldn't be a nested struct in the first place.
Wikipedia says: "In both C and C++ one can define nested struct types, but the scope is interpreted differently (in C++, a nested struct is defined only within the scope/namespace of the outer struct)." (http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B). It doesn't say why, but at least it acknowledges the difference.
You can use the namespace resolution operator to access the struct, however.
Upvotes: 9
Reputation: 9340
because b scope is inside a, you have to use struct a::b
instead (and unlike in C, the struct keyword is optional).
Upvotes: 4