c++ - Reference to static const data objects -
i have set of utility classes store static const data members. need use these data members in functional classes. planning use references (dont want pointers) static const objects, keep getting error below. can please point out logical/technical mistake in code?
#include <string> class staticdata { public: static const int cs = 1; static const staticdata data1; private: staticdata(int id_): _id(id_) //note: private constructer, static access only!! { } int _id; }; const staticdata staticdata::data1(1001); class testreference { public: testreference(): _member(staticdata::data1) {} private: staticdata& _member; };
invalid initialization of reference of type âstaticdata&â expression of type âconst staticdataâ
you're attempting reference const
object through non-const reference.
thus, original object can modified through reference, reference non-const
, , you're breaking contract made when declaring object const
.
there 2 options:
- remove
const
static const staticdata data1;
- make reference
const
:const staticdata& _member;
edit:
as per comment, can have:
class testreference { public: testreference(): _member(&staticdata::data1) {} private: staticdata const * _member; };
this way, can change _member
points (not possible references), can't change object itself.
Comments
Post a Comment