28

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++.
}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
nikel
  • 3,402
  • 11
  • 45
  • 71

4 Answers4

36

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
9

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.

Chris Parton
  • 1,052
  • 9
  • 16
  • 2
    The *why* seems to be avoiding namespace pollution. From http://www2.research.att.com/~bs/sibling_rivalry.pdf: "In C, structure scopes that appear to be nested aren’t, because structure names declared inside are considered to be in the outer scope. This proved to be unmanageable in C++ where nested classes were often used as implementation details. Consequently, C++ adopted nested structure scopes." – UncleBens Nov 27 '11 at 10:54
  • +1 for "probably shouldn't be a nested struct in the first place". – mskfisher Oct 02 '13 at 19:53
4

because b scope is inside a, you have to use struct a::b instead (and unlike in C, the struct keyword is optional).

LeleDumbo
  • 9,192
  • 4
  • 24
  • 38
4

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

ammar26
  • 1,584
  • 4
  • 21
  • 41