-1

so I've been playing around with C++. I was trying to figure out if it's possible to define a structure in the definition of another structure. And here's my code.

#include <iostream>
using namespace std;

int main(){
    struct structure1{
        int integer1;
        struct structure2{
            int integer2;
        }struct2;
    }struct1;
    structure1 *s1 = &struct1;
    s1->integer1 = 50;
    cout<<"STRUCTURE ONE'S INTEGER: "<<s1->integer1<<endl;
    cout<<"STRUCTURE ONE'S STRUCTURE2.integer2: "<<s1->struct2.integer2;
}

OUTPUT:

$ ./a.out
STRUCTURE ONE'S INTEGER: 50
STRUCTURE ONE'S STRUCTURE2.integer2: 0

From what I saw in the output it had seemed to be working. But I just don't understand why or how it worked. Is it good practice? Is there any application to this?

Thanks!

ddolce
  • 661
  • 1
  • 8
  • 25

1 Answers1

0

But I just don't understand why or how it worked.

Why wouldn't it work? It's perfectly legal C++.

Is it good practice?

Depends on how it's used.

Is there any application to this?

Definitely. For example when you only need structure2 inside structure1 and nowhere else. It's good to make its scope as small as possible.

For more information: Why would one use nested classes in C++?

Community
  • 1
  • 1
emlai
  • 39,703
  • 9
  • 98
  • 145