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
Post a Comment