c++ - class member function altering class member variables after they were declared const -


consider following code (not i'm using highlight problem)

class pointarr //creates array of points can recalled object {     public:     pointarr(int, int, bool);     ~pointarr(){};      mutable point array[];      private:     void fillarray(int) const;      int const minpix;     int const mirrors;     bool const canvasfeed; };  void pointarr::fillarray(int mirrors) const {     point zero(0,0);     for(int = 0; < mirrors; i++)     {         array[i] = zero;     } }  pointarr::pointarr(mat dt, int mpx, int mir, bool cf) : dot(dt), minpix(mpx), mirrors(mir), canvasfeed(cf) {     fillarray(mirrors); } 

i'll things out of way first, i'm using gcc c++ compiler natively on linux. using opencv libraries in point variable type holds coordinates in format (x,y). believe uses enough space in memory hold each number 2 integers 4bytes x , 4bytes y.

the problem i'm having variables in constructor declaration (pointarr()) initialise properly, confirmed this, when call fillarray(int) function fills array load of 0 values, (0,0), causes variables mirrors , minpix both change 0 canvasfeed stays when mirrors equal 1.

now, lets specify things, you'll note when mirrors 1, loop within fill array runs once, means array has 1 value (one point). if set mirrors 2 canvasfeed becomes 0. think clear fillarray function assigning same memory used hold private variables array , such changing private variables. problem because need them later.

the thing is, lead believe making private variables const means compiler complain if @ point variables changed compiles fine in case, if i'm honest though don't understand how const should used (hardly even).

so question is, how avoid making array use other memory need still initialise have same amount of element slots mirrors.

i lead believe making private variables const means compiler complain if @ point variables changed.

either misunderstood or made believe incorrectly. there n number of ways in 1 can modify inherently const member , compiler may not in position detect it. eventually, though leads undefined behavior.

you 1 ensure directly or indirectly never modify inherently const data member.


 mutable point array[]; 

is known incomplete array of type point, guaranteed store single element. when use storing more elements write beyond bounds of array causing undefined behavior.

you need use vector:

mutable std::vector<point> array; 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -