pointers - Specifying "const" when overloading operators in c++ -
code:
4: typedef unsigned short ushort; 5: #include <iostream.h> 6: 7: class counter 8: { 9: public: 10: counter(); 11: ~counter(){} 12: ushort getitsval()const { return itsval; } 13: void setitsval(ushort x) {itsval = x; } 14: void increment() { ++itsval; } 15: const counter& operator++ (); 16: 17: private: 18: ushort itsval; 19: 20: }; 21: 22: counter::counter(): 23: itsval(0) 24: {}; 25: 26: const counter& counter::operator++() 27: { 28: ++itsval; 29: return *this; 30: } 31: 32: int main() 33: { 34: counter i; 35: cout << "the value of " << i.getitsval() << endl; 36: i.increment(); 37: cout << "the value of " << i.getitsval() << endl; 38: ++i; 39: cout << "the value of " << i.getitsval() << endl; 40: counter = ++i; 41: cout << "the value of a: " << a.getitsval(); 42: cout << " , i: " << i.getitsval() << endl; 48: return 0; 49: }
i'm studying overloading operators in c++ , can't wrap head around "const" specifier in line 26. way understood constant reference not allowed change value stored in reference. inside operator++ function (lines 26-30), member variable "itsval" incremented. doesn't violate "const" requirement in function's definition?
the operator returning reference internal parameter const reference, means client code can not modify reference receive operator.
if, on other hand member function const:
const counter& counter::operator++() const
then function not allowed modify of members. stands can modification wants before returning reference.
Comments
Post a Comment