-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
  • 739
  • 2
  • 10
  • 30
  • There doesn't seem to be anything wrong besides the lack of an initialization of `integer2`. – E_net4 Mar 20 '15 at 18:00
  • @E_net4 I did, but what I typed seemed to be cutoff for some reason, I've put the rest back in. – ddolce Mar 20 '15 at 18:02
  • Nevertheless, your question makes it look like you haven't read about aggregate types in C++ and the fact that you can nest them. – E_net4 Mar 20 '15 at 18:03
  • 1
    I can't cast it but this is a dupe of http://stackoverflow.com/q/4571355/560648 – Lightness Races in Orbit Mar 20 '15 at 18:03
  • It works because it is valid syntax. I have seen this used before. Normally declaring a enum or another struct that will only ever be used by that class or struct internally. – marsh Mar 20 '15 at 18:08

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
Emil Laine
  • 41,598
  • 9
  • 101
  • 157