Handout 17b

Using const with classes


1    #include <iostream.h>
2
3    // example of using the const qualifier in classes
4    // illustrating the principle of least privilege
5
6    class One {
7    public:
8       One();
9       One(int, float);
10      ~One();
11      One get() const;
12      One set(int, float);
13      const One giveConst();
14      One addVals(const One);
15      void showValues() const;
16      void showValues();
17   private:
18       float fValue;
19       int iValue;
20   };
21
22   // ====================================================
23
24   One::One() {
25      fValue = 0.0; iValue = 0;  
26   }
27
28   One::~One() {
29      // do nothing  
30   }
31
32   One::One(int i, float f) {
33       iValue = i; fValue = f;
34   }
35
36   One One::get() const {
37       return *this;
38   }
39
40   One One::set(int i, float f) {
41       iValue = i; fValue = f;
42       return *this;
43   }
44
45   const One One::giveConst() {
46       return *this;
47   }
48
49   One One::addVals(const One parm) {
50      iValue = iValue + parm.iValue;
51      fValue = fValue + parm.fValue;
52      return *this;
53   }
54
55   void One::showValues() const {
56       cout << "i = " << iValue << "  f = " << fValue << 
57         " output from const showValues method" << endl;
58   }
59
60   void One::showValues() {
61       cout << "i = " << iValue << "  f = " << fValue << 
62         " output from non-const showValues method" << endl;
63   }
64
65   // ====================================================
66
67   int main() {
68      One A, B(1,2.0);
69      const One C(3,2.0);
70
71      // display the values
72      A.showValues();
73      B.showValues();
74      C.showValues();
75
76       // create some new instances
77      One tempNonConst = A.get();
78      const One tempConst = A.get();
79
80   //  RHS is const, but is converted to non-const on LHS
81      const One X = B.giveConst();
82      One Y = B.giveConst();
83
84      (Y.addVals(tempConst)).showValues();
85      (Y.addVals(tempNonConst)).showValues();
86
87   //   compiler will flag the following
88   //  (X.addVals(tempNonConst)).showValues();
89
90      return 0;
91   }
92
93   /* program output
94
95   i = 0  f = 0 output from non-const showValues method
96   i = 1  f = 2 output from non-const showValues method
97   i = 3  f = 2 output from const showValues method
98   i = 1  f = 2 output from non-const showValues method
99   i = 1  f = 2 output from non-const showValues method
100
101  */


source code.