Alex Rivera | Logout

Nested structures in C and C++

Asked 2011-11-27T07:10:28.707
29

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++.
}
c++ c
Edit
Report

1 Answer

10

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.

answered 2011-11-27T07:16:38.443

Your Answer