Example by: Ira Oldham, References: Savitch eighth edition, section 10.2; Gaddis seventh edition, section 13.2
Now that we have member functions that can access the data, we can make the data private, so only member functions can access the data.
1 struct Sum
2 {
3 private:
4 int a;
5 int b;
6 public:
7 int getA() {return a;}
8 int getB() {return b;}
9 void putA(int value) {a = value;}
10 void putB(int value) {b = value;}
11 int sum();
12 };
13 int main(void)
14 {
15 Sum x;
16 int result;
17 x.putA(3);
18 x.putB(4);
19 result = x.sum();
20 cout << "x.a: " << x.getA() << endl;
21 cout << "x.b: " << x.getB() << endl;
22 cout << "sum: " << x.sum() << endl;
23 return 0;
24 }
25 int Sum::sum()
26 {
27 return a + b;
28 }
x.a: 3 x.b: 4 sum: 7
Private member data can only be accessed by member functions.
Making all the member data private is an important step toward object oriented programming. In object orientated programming this is called encapsulation. It is essential in object oriented programming to always make all member data private.