I'd like to add another use case for an internal struct
/class
and its usability. An inner struct
is often used to declare a data only member of a class that packs together relevant information and as such we can enclose it all in a struct
instead of loose data members lying around.
The inner struct
/class
is but a data only compartment, ie it has no functions (except maybe constructors).
#include <iostream>
class E
{
// E functions..
public:
struct X
{
int v;
// X variables..
} x;
// E variables..
};
int main()
{
E e;
e.x.v = 9;
std::cout << e.x.v << '\n';
E e2{5};
std::cout << e2.x.v << '\n';
// You can instantiate an X outside E like so:
//E::X xOut{24};
//std::cout << xOut.v << '\n';
// But you shouldn't want to in this scenario.
// X is only a data member (containing other data members)
// for use only inside the internal operations of E
// just like the other E's data members
}
This practice is widely used in graphics, where the inner struct
will be sent as a Constant Buffer to HLSL.
But I find it neat and useful in many cases.
struct
is a class) does not denote data nesting. It merely nests the class definitions. So you can declare a variable likeE::X object; object.v = 10;
. Nesting does have some effect on accessibility of names, but those rules are subtle and have been changed quite a number of times, and AFAIK nobody really know what they are / should be. In practice, when we use nesting we go with what the compilers allow, and just hope that that's more or less what the formal rules also say. Cheers & hth.,