/* * A few places where "const" is commonly seen */ #include using namespace std; const double PI = 3.141592653; #define PIC 3.141592653 void square(int &x){ x *= x; } void pointer_square(int *x){ *x *= *x; } void print(const int &x){ // If you take cout << "The parameter was: " << x << endl; } int find_half(const int &x){ return x/2; } class fox { public: int length; string name; fox(int l, string n) : length(l), name(n) {} // void enlongate(fox *this){ void enlongate(){ this->length++; } // int getLength()(const fox *this){ int getLength() const { return this->length; } ~fox(){ cout << this->name << " has been discarded with length " << this->length << " and address " << this << endl; } }; void enlongate_anyway(const fox& tostretch){ void* e = (void*)&tostretch; ((fox*)e)->enlongate(); ((fox*)((void*)&tostretch))->enlongate(); } // Copying classes, references in C++, const reference, etc. void stretch(fox tostretch){ cout << "Lengthening " << tostretch.name << endl; tostretch.enlongate(); tostretch.enlongate(); cout << "After Lengthening, final length is " << tostretch.length << endl; } int main(){ const int unchangeable = 10; // square(unchangeable); // Can't do this, because it would change x! int z = 20; square(z); pointer_square(&z); cout << "z = " << z << endl; print(unchangeable); cout << "Half of unchangeable = " << find_half(unchangeable) << endl; fox snake(30, "Snake"); const fox clearwater(32, "Clearwater"); snake.enlongate(); // clearwater.enlongate(); // Can't do that! clearwater is a "const fox" clearwater.getLength(); // This is ok, because getLength is a const method fox extra = clearwater; stretch(extra); size_t Arr[] = {2, 3, 4, 7, 8, 9}; auto x = Arr[3]; cout << sizeof(x) << endl; for(auto &i : Arr) i *= 400; for(const auto &i : Arr) cout << "i = " << i << endl; enlongate_anyway(extra); cout << "After enlongate_anyway, extra has a length of " << extra.length << endl; return 0; }