declare member function

Example by: Ira Oldham, References: Savitch eighth edition, section 10/2; Gaddis seventh edition, section 13.2

Member functions can be declared within the structure, and defined later.

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

A member function can be declared within a structure. Later when the complte function definition is written, a scope resolution operation must be applied to the name of the function, to make it a part of the structure.

STYLE NOTE - When a member function is only a statement or two, it is easier to just write the complete function definition within the structure. When the function is more than a few statements, it is best to declare it in the structure, and then use scope resolution when you write the function later.