Website For Developers

Nested Structures in C++



Syntax

structouterStruct {
  char name[25];
  int age;
};

structinnerStruct {
  outerStructure obj;
};

Syntax of accessing members

int main() {
  innerStruct object;
  object.obj.name; //accessing name variable
  object.obj.age; //accessing age variable
}


Example of Nested Structures in C++

#include<iostream>
#include<conio.h>
using namespace std;
struct info {
  char name[30];
  int age;
  int contact;
};

struct address {
  char country[30];
  char city[30];
  info obj;
};

int main() {
  address ad;
  cout<<"Enter Your Name: ";
  cin>>ad.obj.name;
  cout<<"Enter Your Age: ";
  cin>>ad.obj.age;
  cout<<"Enter Your Contact Number: ";
  cin>>ad.obj.contact;
  cout<<"Enter Your Current Country: ";
  cin>>ad.country;
  cout<<"Enter Your Current City: ";
  cin>>ad.city;
  getch();
  return 0;
}

Output

Enter Your Name: Faizan
Enter Your Age: 23
Enter Your Contact Number: 123456789
Enter Your Current Country: Australia
Enter your Current City: Sydney



Example of Nested Structures in C++

//Example with multiple Nested Structures

#include<iostream>
#include<conio.h>
using namespace std;
struct info {
  char name[30];
  int age;
  int contact;
};

struct marks {
  char schoolGrade;
  char collegeGrade[30];
};

struct address {
  char country[30];
  char city[30];
  info obj1;
  marks obj2;
};

int main() {
  address ad;
  cout<<"Enter Your Name: ";
  cin>>ad.obj1.name;
  cout<<"Enter Your Age: ";
  cin>>ad.obj1.age;
  cout<<"Enter Your Contact Number: ";
  cin>>ad.obj1.contact;
  cout<<"Enter Your School Grade: ";
  cin>>ad.obj2.schoolGrade;
  cout<<"Enter Your College Grade: ";
  cin>>ad.obj2.collegeGrade;
  cout<<"Enter Your Current Country: ";
  cin>>ad.country;
  cout<<"Enter Your Current City: ";
  cin>>ad.city;

  getch();
  return 0;
}

Output

Enter Your Name: Max
Enter Your Age: 21
Enter Your Contact Number: 123
Enter Your School Grade: B
Enter Your College Grade: A
Enter Your Current Country: England
Enter Your Current City: London