c++ - const correctness and member pointers -


i have const on accelerate method, yet can call power method. way stop this.

class engine{ public:     void power(){     } };  class car{ public:     car() : p(new engine()){}      void accelerator() const{         p->power();     }      private:         engine* p; }; 

for car, const method methods not modify car member variables.

so, long car::accelerator not make p point different location, valid.

since p not modified in accelerator (meaning not point different memory address), program valid.

the moment make p point different location, program fails compile:

  void accelerator() const {         p= nullptr; //wrong   }  

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -