Nested structs
- C++ course
- Beginner
- Lesson 98/116
- 5 min
Learn to use a struct inside another struct.
Nested structs
A member of a struct can itself be another struct. This is the basic way to group related data hierarchically.
struct Address {
string city;
string street;
};
struct Person {
string name;
Address home;
};Here the Person struct contains an Address member. To access an inner member, you chain dots: p.home.city. This lets you model real objects more naturally.
Using nested structs
In a nested struct, after defining the outer struct you can assign inner members one by one. You can also define the inner struct separately first and then assign it to the outer struct.
Person p;
p.name = "Ayşe";
p.home.city = "İstanbul";
p.home.street = "Çiçek Sokak";Here p.home behaves like an Address; its members are assigned with .city and .street. This layout keeps the address as a separate struct while staying readable.
Practice Define Person and Address
Define struct Address { string city; string street; };. Then define struct Person { string name; Address home; };. In main, create Person p;; assign p.name = "Ayşe"; and p.home.city = "İstanbul";. Print cout << p.name << " - " << p.home.city << endl;.
Starter code
#include <iostream>
#include <string>
using namespace std;
// Define the Address struct
// Define the Person struct
int main() {
// create Person p; assign name and home.city, print
return 0;
}Sample solution
#include <iostream>
#include <string>
using namespace std;
struct Address {
string city;
string street;
};
struct Person {
string name;
Address home;
};
int main() {
Person p;
p.name = "Ayşe";
p.home.city = "İstanbul";
cout << p.name << " - " << p.home.city << endl;
return 0;
}Expected output
Ayşe - Istanbul
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does p.home.city do for Person p;?
- raises an error
- creates a new city
- accesses the inner city member Correct answer
- writes city for Person
Explanation: The dot chain accesses the inner member.
2 Fill in the blank: inner member access
Person p;
p.____.city = "İzmir";
Person p;
p.home.city = "İzmir";
Explanation: The p.home.city chain reaches the inner member.
3 Match each expression with its result
| Term | Meaning |
|---|---|
p.name |
person name |
p.home.city |
city |
p.home.street |
street |