Loading lessons...
Member Variables and Member Selection
Member Variables and Member Selection
The key to reading or changing a struct is the member selection operator - the dot .. It connects an object with one of its members.
A struct full of members
#include <iostream>
using namespace std;
struct Person {
string name;
int age;
};
int main() {
Person bob;
bob.name = "Bob";
bob.age = 80;
cout << bob.name << endl; // Bob
return 0;
}
The members name and age are member variables: ordinary variables that live inside each Person object.
Reading a member
string whom = bob.name; // copy the member out
cout << bob.age; // use it directly
Writing a member
The dot also works for assignment:
bob.age = 80; // store the value on the right
bob.name = "Bob"; // replace the old name
Members behave like normal variables
A member supports everything its type supports - assign, print, compare, do math. It just belongs to the object instead of living alone.
Arrays of structs
A struct is a type, so it can be the element type of an array:
int main() {
Person team[3];
team[0].name = "Alice";
team[0].age = 25;
team[1].name = "Bob";
team[1].age = 80;
cout << team[0].name << endl; // Alice
return 0;
}
team[0]selects the first object..namethen selects its member.- Combined:
team[0].name.
TL;DR
- Members are the variables that live inside an object.
- The dot erases a member:
cout << bob.name;. - The dot writes a member:
bob.age = 80;. team[0].name= pick the element first, then the member.- Member variables act like ordinary variables of their type.