structure function

Example by: Ira Oldham, References: Savitch eighth edition, section 10.2; Gaddis seventh edition, section 13.2

A structure can also contain a member that is a function.

1  struct Sum
2  {
3  int a;
4  int b;
5  int sum()
6  {
7    return a + b;
8  }
9  };
10 int main(void)
11 {
12   Sum x;
13   int result;
14   x.a = 3;
15   x.b = 4;
16   result = x.sum();
17   cout << "x.a: " << x.a     << endl;
18   cout << "x.b: " << x.b     << endl;
19   cout << "sum: " << x.sum() << endl;
20   return 0;
21 }
x.a: 3
x.b: 4
sum: 7

A structure can contain member functions. To call a member function, specify the name of the structure variable, a dot, and the member function. Within the member function, the member data are accessed without using a variable name and a dot.