what is the best and how declare const in function of c++ -


i have these code

#include <iostream> using namespace std; class ex; class exx;  class ex { public:     int _val;     int const *_p_val;     void setptrval(int * const &val) {         _p_val=val;     } };  class exx { public:     ex const *_ex;     void setex(ex const &ex)     {         _ex=&ex;     } };  int main() {     ex x;     int i=10;     x.setptrval(&i);     exx xx;     xx.setex(x);     int y=20;     cout<<*(xx._ex->_p_val)<<endl;     x.setptrval(&y);     cout<<*(xx._ex->_p_val)<<endl;     cout<<*x._p_val<<endl;     return 0; } 

1: can see, ex x not const of ex class. , ex const *_ex; pointer point ex const. why above ok?

2: const in void setex(ex const &ex) means can't modify ex in function body?

3: how fix setter function member pointer variable if want prototype above (suppose sercurity reason)?

ok. if ex const *_ex; become ex *_ex; so, in setter function, want prototype not modify argument object, above. how function body become?

  1. a pointer (or reference) const not have point const object. means can't used modify object points to; can safely point either const or non-const object.

  2. yes. specifically, means reference passed function argument can't used modify object.

  3. it's better include const if don't need use modification. prevent accidental modification, , allow point const objects.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -