2.1. First, There Was struct

[ fromfile: classes.xml id: structs ]

Example 2.1. src/structdemo/demostruct.h

[ . . . . ]
struct Fraction {
    int numer, denom;
    string description;
};
[ . . . . ]

Example 2.2. src/structdemo/demostruct.cpp

[ . . . . ]
void printFraction(Fraction f) {        1
    cout << f.numer << "/" << f.denom << endl;
    cout << "  =? " << f.description << endl; 
}
int main() {  
    Fraction f1;
    f1.numer = 4;
    f1.denom = 5;
    f1.description = "four fifths";   
    Fraction f2 = {2, 3, "two thirds"}; 2
    
    f1.numer = f1.numer + 2;            3
    printFraction(f1);
    printFraction(f2);
    return 0;
}
Output:

  6/5
  =? four fifths
  2/3  
  =? two thirds



1

Passing a struct by value could be expensive if it has large components.

2

Member Initialization.

3

Client code can change individual data members.